JavaScript and React course ยท Module 7: Styling and Animations

Styled Components - Cosmic Fusion of JSX and CSS

24 min read ยท
In this lesson10

On our cosmic journey through the world of styling in React, we arrive at a fascinating technology that blurs the boundaries between code and style. Styled Components is like an advanced interstellar ship that combines the DNA of two worlds - JavaScript and CSS - creating a new life form perfectly adapted to the React ecosystem.

What Are Styled Components?

Styled Components is one of the most popular CSS-in-JS libraries that allows writing actual CSS directly in JavaScript/JSX files, while creating normal React components. This revolutionary approach to styling lets us think of our components as fully enclosed, autonomous units where both logic and style are gathered in one place.

Think of components like spaceship modules - each contains both its function (engines, life support systems, navigation) and its appearance (control panels, indicators, interfaces) - all hermetically sealed in one coherent unit.

Installation and Configuration

Before we begin our adventure with Styled Components, we need to install the library:

npm install styled-components
# or
yarn add styled-components
# or
pnpm add styled-components

For TypeScript users, it is worth adding types as well:

npm install @types/styled-components

Styled Components Basics

Creating a Simple Styled Component

Creating styled components is extremely intuitive. Just use the styled function imported from the library, followed by the HTML tag name to which you want to apply styles:

import styled from 'styled-components';

// Creating a styled button
const Button = styled.button`
  background-color: #4a90e2;
  color: white;
  padding: 10px 15px;
  border: none;
  border-radius: 4px;
  font-weight: bold;
  cursor: pointer;
  transition: all 0.3s ease;

  &:hover {
    background-color: #357ae8;
    transform: translateY(-2px);
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
  }

  &:active {
    transform: translateY(1px);
  }
`;

// Using the component
function App() {
  return (
    <div>
      <h1>Command Center</h1>
      <Button>Initiate launch procedure</Button>
    </div>
  );
}

In the example above, we created a styled Button component that works like a normal HTML button but has predefined styles. Notice the characteristic syntax using backticks (``), which allows writing multi-line CSS. Furthermore, we can use the & selector like in Sass to refer to the component itself.

Style Inheritance

We can extend existing styled components by adding new styles:

// Base button
const Button = styled.button`
  padding: 10px 15px;
  border: none;
  border-radius: 4px;
  font-weight: bold;
  cursor: pointer;
  transition: all 0.3s ease;
`;

// Extending the base button
const PrimaryButton = styled(Button)`
  background-color: #4a90e2;
  color: white;

  &:hover {
    background-color: #357ae8;
  }
`;

// Another extension
const DangerButton = styled(Button)`
  background-color: #e74c3c;
  color: white;

  &:hover {
    background-color: #c0392b;
  }
`;

Working with Props (Parameters)

One of the most powerful features of Styled Components is the ability to dynamically style based on props passed to the component:

const Button = styled.button`
  padding: 10px 15px;
  border: none;
  border-radius: 4px;
  font-weight: bold;
  cursor: pointer;
  transition: all 0.3s ease;

  /* Dynamic colors based on props */
  background-color: ${props =>
    props.primary ? '#4a90e2' : props.danger ? '#e74c3c' : props.success ? '#2ecc71' : '#95a5a6'};
  color: white;

  /* Dynamic size */
  font-size: ${props => (props.large ? '18px' : '14px')};
  padding: ${props => (props.large ? '12px 20px' : '8px 12px')};

  /* Disabled button */
  opacity: ${props => (props.disabled ? 0.5 : 1)};
  cursor: ${props => (props.disabled ? 'not-allowed' : 'pointer')};

  &:hover {
    ${props => !props.disabled && `
      transform: translateY(-2px);
      box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
    `}
  }
`;

// Usage with different props
function ActionPanel() {
  return (
    <div>
      <Button>Normal</Button>
      <Button primary>Primary</Button>
      <Button danger>Delete</Button>
      <Button success large>Save</Button>
      <Button disabled>Unavailable</Button>
    </div>
  );
}

In the example above, the button style changes depending on the passed props. We can pass any props to our styled components and then use them in expressions inside template literals.

Prop-forwarding and HTML Attributes

Styled Components automatically forward all unused props to the DOM element:

// This button will have type "submit" and onClick handling
function FormSubmit() {
  return (
    <Button
      type="submit"
      onClick={() => console.log('Form submitted!')}
    >
      Submit
    </Button>
  );
}

Styling Existing Components

We can also style existing React components, as long as they accept a className prop:

// Regular React component
function CustomInput({ className, ...props }) {
  return (
    <input
      className={className}
      {...props}
    />
  );
}

// Styling an existing component
const StyledCustomInput = styled(CustomInput)`
  border: 2px solid #3498db;
  border-radius: 4px;
  padding: 8px 12px;
  width: 100%;
  font-size: 16px;

  &:focus {
    outline: none;
    border-color: #2980b9;
    box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.3);
  }
`;

Advanced Styled Components Features

Global Styles

Styled Components also offers a GlobalStyle component for defining global styles:

import { createGlobalStyle } from 'styled-components';

const GlobalStyle = createGlobalStyle`
  /* CSS Reset */
  *, *::before, *::after {
    box-sizing: border-box;
    margin: 0;
    padding: 0;
  }

  /* Global variables */
  :root {
    --primary-color: #4a90e2;
    --secondary-color: #8a2be2;
    --success-color: #2ecc71;
    --danger-color: #e74c3c;
    --warning-color: #f1c40f;
    --text-light: #ecf0f1;
    --text-dark: #2c3e50;
    --background-dark: #1a1a2e;
    --background-light: #f5f5f5;
  }

  body {
    font-family: 'Space Grotesk', sans-serif;
    line-height: 1.6;
    background-color: var(--background-dark);
    color: var(--text-light);
  }

  a {
    color: var(--primary-color);
    text-decoration: none;
  }

  button {
    font-family: inherit;
  }
`;

// Using GlobalStyle in the application
function App() {
  return (
    <>
      <GlobalStyle />
      <div>
        {/* Application content */}
      </div>
    </>
  );
}

Theming

One of the greatest advantages of Styled Components is theme support:

import { ThemeProvider } from 'styled-components';

// Theme definition
const darkTheme = {
  colors: {
    primary: '#4a90e2',
    secondary: '#8a2be2',
    success: '#2ecc71',
    danger: '#e74c3c',
    warning: '#f1c40f',
    background: '#1a1a2e',
    text: '#ecf0f1',
    muted: '#95a5a6'
  },
  fonts: {
    body: "'Space Grotesk', sans-serif",
    heading: "'Nova Mono', monospace"
  },
  spacing: {
    xs: '4px',
    sm: '8px',
    md: '16px',
    lg: '24px',
    xl: '32px'
  },
  borderRadius: {
    small: '4px',
    medium: '8px',
    large: '12px',
    round: '50%'
  },
  shadows: {
    small: '0 2px 4px rgba(0, 0, 0, 0.1)',
    medium: '0 4px 8px rgba(0, 0, 0, 0.2)',
    large: '0 8px 16px rgba(0, 0, 0, 0.3)'
  }
};

// Alternative theme
const lightTheme = {
  colors: {
    primary: '#3498db',
    secondary: '#9b59b6',
    success: '#27ae60',
    danger: '#c0392b',
    warning: '#f39c12',
    background: '#f5f5f5',
    text: '#2c3e50',
    muted: '#7f8c8d'
  },
  // Other properties same as in darkTheme
  fonts: darkTheme.fonts,
  spacing: darkTheme.spacing,
  borderRadius: darkTheme.borderRadius,
  shadows: darkTheme.shadows
};

// Styled component using the theme
const Card = styled.div`
  background-color: ${props =>
    props.theme.colors.background === '#1a1a2e' ? '#252941' : '#ffffff'};
  color: ${props => props.theme.colors.text};
  border-radius: ${props => props.theme.borderRadius.medium};
  padding: ${props => props.theme.spacing.md};
  box-shadow: ${props => props.theme.shadows.small};

  transition: all 0.3s ease;

  &:hover {
    box-shadow: ${props => props.theme.shadows.medium};
  }
`;

// Styled button using the theme
const Button = styled.button`
  background-color: ${props => props.theme.colors.primary};
  color: white;
  padding: ${props => props.theme.spacing.sm} ${props => props.theme.spacing.md};
  border: none;
  border-radius: ${props => props.theme.borderRadius.small};
  font-family: ${props => props.theme.fonts.body};
  cursor: pointer;

  &:hover {
    background-color: ${props => {
      const color = props.theme.colors.primary;
      // Simple darker color function
      return color.replace(/rgb\((\d+), (\d+), (\d+)\)/, (_, r, g, b) =>
        `rgb(${Math.max(0, r - 20)}, ${Math.max(0, g - 20)}, ${Math.max(0, b - 20)})`
      );
    }};
  }
`;

// Using ThemeProvider and themed components
function App() {
  const [darkMode, setDarkMode] = useState(true);
  const theme = darkMode ? darkTheme : lightTheme;

  return (
    <ThemeProvider theme={theme}>
      <GlobalStyle />
      <AppContainer>
        <Header>
          <h1>Cosmic Command Center</h1>
          <Button onClick={() => setDarkMode(!darkMode)}>
            Switch to {darkMode ? "light" : "dark"} mode
          </Button>
        </Header>

        <Card>
          <h2>Control Panel</h2>
          <p>Here you can manage your cosmic mission.</p>
          <Button>Launch</Button>
        </Card>
      </AppContainer>
    </ThemeProvider>
  );
}

Animations

Styled Components allows easy animation creation using the keyframes helper function:

import styled, { keyframes } from 'styled-components';

// Animation definition
const pulse = keyframes`
  0% {
    opacity: 1;
    transform: scale(1);
  }
  50% {
    opacity: 0.8;
    transform: scale(1.05);
  }
  100% {
    opacity: 1;
    transform: scale(1);
  }
`;

const rotate = keyframes`
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
`;

// Using animations in a component
const PulsingButton = styled.button`
  background-color: #e74c3c;
  color: white;
  padding: 12px 24px;
  border: none;
  border-radius: 4px;
  font-weight: bold;

  /* Applying animation */
  animation: ${pulse} 2s infinite ease-in-out;
`;

const Spinner = styled.div`
  width: 40px;
  height: 40px;
  border: 4px solid rgba(255, 255, 255, 0.3);
  border-top: 4px solid #3498db;
  border-radius: 50%;

  /* Rotation animation */
  animation: ${rotate} 1s linear infinite;
`;

// Conditional animations
const AlertBadge = styled.span`
  display: inline-block;
  padding: 4px 8px;
  background-color: red;
  color: white;
  border-radius: 10px;
  font-size: 12px;

  /* Animation only when there is a critical alert */
  animation: ${props => props.critical ?
    css`${pulse} 1s infinite` : 'none'};
`;

Pseudo-elements and Pseudo-classes

Styled Components support all CSS pseudo-elements and pseudo-classes:

const HoverCard = styled.div`
  position: relative;
  padding: 20px;
  background-color: #252941;
  border-radius: 8px;
  transition: all 0.3s ease;

  /* Pseudo-classes */
  &:hover {
    transform: translateY(-5px);
    box-shadow: 0 10px 20px rgba(0, 0, 0, 0.2);
  }

  &:active {
    transform: translateY(-2px);
  }

  /* Pseudo-elements */
  &::before {
    content: "";
    position: absolute;
    top: -10px;
    left: -10px;
    right: -10px;
    bottom: -10px;
    border-radius: 12px;
    background: linear-gradient(45deg, #4a90e2, #8a2be2);
    z-index: -1;
    opacity: 0;
    transition: opacity 0.3s ease;
  }

  &:hover::before {
    opacity: 1;
  }

  /* Nested selectors */
  h3 {
    margin-bottom: 10px;
    color: #ecf0f1;
  }

  p {
    color: #bdc3c7;
  }

  /* Complex selectors */
  &:hover h3 {
    color: #4a90e2;
  }
`;

Media Queries

Styled Components excellently supports media queries, enabling the creation of responsive components:

const ResponsiveContainer = styled.div`
  padding: 20px;
  background-color: #252941;
  border-radius: 8px;

  /* Base width */
  width: 100%;

  /* Media queries */
  @media (min-width: 768px) {
    width: 750px;
    margin: 0 auto;
  }

  @media (min-width: 992px) {
    width: 970px;
  }

  @media (min-width: 1200px) {
    width: 1170px;
  }

  /* Responsive style changes */
  h1 {
    font-size: 24px;

    @media (min-width: 768px) {
      font-size: 32px;
    }
  }

  /* We can use media queries inside conditions */
  display: ${props => props.hidden ?
    `
      none;
      @media (min-width: 768px) {
        display: block;
      }
    ` : 'block'
  };
`;

Helpers and Utility Functions

Styled Components provides several useful tools, like css for reusing style fragments:

import styled, { css } from 'styled-components';

// Creating reusable style fragments
const flexCenter = css`
  display: flex;
  justify-content: center;
  align-items: center;
`;

const buttonBase = css`
  padding: 10px 15px;
  border: none;
  border-radius: 4px;
  font-weight: bold;
  cursor: pointer;
  transition: all 0.3s ease;
`;

const dangerStyles = css`
  background-color: #e74c3c;
  color: white;

  &:hover {
    background-color: #c0392b;
  }
`;

// Using fragments in components
const FlexContainer = styled.div`
  ${flexCenter}
  gap: 20px;
  flex-wrap: wrap;
`;

const Button = styled.button`
  ${buttonBase}

  background-color: #4a90e2;
  color: white;

  &:hover {
    background-color: #357ae8;
  }

  ${props => props.danger && dangerStyles}
`;

Advanced Patterns and Techniques

Reusable Components and Their Variations

One of the best practices in Styled Components is creating reusable base components with variations:

// Base button component
const BaseButton = styled.button`
  padding: 10px 15px;
  border: none;
  border-radius: 4px;
  font-weight: bold;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 14px;
`;

// Button variants
const PrimaryButton = styled(BaseButton)`
  background-color: ${props => props.theme.colors.primary};
  color: white;

  &:hover {
    background-color: ${props => darken(0.1, props.theme.colors.primary)};
  }
`;

const SecondaryButton = styled(BaseButton)`
  background-color: transparent;
  color: ${props => props.theme.colors.primary};
  border: 2px solid ${props => props.theme.colors.primary};

  &:hover {
    background-color: ${props => rgba(props.theme.colors.primary, 0.1)};
  }
`;

const DangerButton = styled(BaseButton)`
  background-color: ${props => props.theme.colors.danger};
  color: white;

  &:hover {
    background-color: ${props => darken(0.1, props.theme.colors.danger)};
  }
`;

// Button sizes
const SmallButton = css`
  padding: 6px 10px;
  font-size: 12px;
`;

const LargeButton = css`
  padding: 12px 20px;
  font-size: 16px;
`;

// Higher-order component for size
const sizedButton = (Component) => styled(Component)`
  ${props => props.small && SmallButton}
  ${props => props.large && LargeButton}
`;

// Creating variants with sizes
const SizedPrimaryButton = sizedButton(PrimaryButton);
const SizedSecondaryButton = sizedButton(SecondaryButton);
const SizedDangerButton = sizedButton(DangerButton);

// Usage
function ActionPanel() {
  return (
    <div>
      <SizedPrimaryButton>Normal</SizedPrimaryButton>
      <SizedPrimaryButton small>Small</SizedPrimaryButton>
      <SizedPrimaryButton large>Large</SizedPrimaryButton>

      <SizedSecondaryButton>Normal</SizedSecondaryButton>
      <SizedDangerButton large>Big alert</SizedDangerButton>
    </div>
  );
}

Creative Use of the as Attribute

Styled Components allows changing the HTML element used by a component via the as prop:

const Button = styled.button`
  background-color: #4a90e2;
  color: white;
  padding: 10px 15px;
  border: none;
  border-radius: 4px;
  font-weight: bold;
  cursor: pointer;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  text-decoration: none;
`;

function App() {
  return (
    <div>
      <Button>Normal button</Button>

      {/* Rendering as a link */}
      <Button as="a" href="/destination">
        Button as link
      </Button>

      {/* Rendering as another element */}
      <Button as="div" role="button" tabIndex={0}>
        Button as div
      </Button>

      {/* We can use another React component */}
      <Button as={Link} to="/dashboard">
        Button as router Link
      </Button>
    </div>
  );
}

Conditional Styling

Styled Components allows very detailed conditional styling:

const AlertBox = styled.div`
  padding: 15px;
  border-radius: 8px;
  margin-bottom: 20px;
  display: flex;
  align-items: center;

  /* Changing background color based on alert type */
  background-color: ${props =>
    props.type === 'success' ? '#d4edda' :
    props.type === 'danger' ? '#f8d7da' :
    props.type === 'warning' ? '#fff3cd' :
    props.type === 'info' ? '#d1ecf1' :
    '#e2e3e5'
  };

  /* Changing text color */
  color: ${props =>
    props.type === 'success' ? '#155724' :
    props.type === 'danger' ? '#721c24' :
    props.type === 'warning' ? '#856404' :
    props.type === 'info' ? '#0c5460' :
    '#383d41'
  };

  /* Changing border */
  border: 1px solid ${props =>
    props.type === 'success' ? '#c3e6cb' :
    props.type === 'danger' ? '#f5c6cb' :
    props.type === 'warning' ? '#ffeeba' :
    props.type === 'info' ? '#bee5eb' :
    '#d6d8db'
  };

  /* Changing icons */
  &::before {
    content: "${props =>
      props.type === 'success' ? 'OK' :
      props.type === 'danger' ? 'ร—' :
      props.type === 'warning' ? '!' :
      props.type === 'info' ? 'โ„น' :
      'โ„น'
    }";
    margin-right: 10px;
    font-size: 18px;
  }

  /* We can also use nested conditions and functions */
  ${props => {
    if (props.dismissable) {
      return `
        padding-right: 40px;
        position: relative;
      `;
    }
  }}
`;

// Close button for dismissable alerts
const CloseButton = styled.button`
  position: absolute;
  top: 10px;
  right: 10px;
  background: none;
  border: none;
  font-size: 20px;
  cursor: pointer;
  color: inherit;
  opacity: 0.5;

  &:hover {
    opacity: 1;
  }
`;

// Using the component
function Notifications() {
  return (
    <div>
      <AlertBox type="success">
        Mission completed successfully!
      </AlertBox>

      <AlertBox type="danger" dismissable>
        Warning: System failure detected!
        <CloseButton>&times;</CloseButton>
      </AlertBox>

      <AlertBox type="warning">
        Warning: Low fuel level.
      </AlertBox>

      <AlertBox type="info">
        Information: Approaching space station.
      </AlertBox>
    </div>
  );
}

Practical Example: Cosmic Dashboard

Let's see how to create a more complex interface using Styled Components:

import React, { useState } from 'react';
import styled, { ThemeProvider, createGlobalStyle, keyframes } from 'styled-components';

// ========== Theme Definition ==========
const theme = {
  colors: {
    primary: '#4a90e2',
    secondary: '#8a2be2',
    success: '#2ecc71',
    danger: '#e74c3c',
    warning: '#f1c40f',
    info: '#3498db',
    background: '#0f1429',
    cardBg: '#1a1f3c',
    text: '#ecf0f1',
    textMuted: '#95a5a6',
    border: '#2c3e50'
  },
  spacing: {
    xs: '4px',
    sm: '8px',
    md: '16px',
    lg: '24px',
    xl: '32px'
  },
  fonts: {
    body: "'Space Grotesk', sans-serif",
    mono: "'JetBrains Mono', monospace"
  },
  borderRadius: {
    sm: '4px',
    md: '8px',
    lg: '16px'
  }
};

// ========== Global Style ==========
const GlobalStyle = createGlobalStyle`
  * {
    box-sizing: border-box;
    margin: 0;
    padding: 0;
  }

  body {
    font-family: ${props => props.theme.fonts.body};
    background-color: ${props => props.theme.colors.background};
    color: ${props => props.theme.colors.text};
    line-height: 1.6;
  }

  h1, h2, h3, h4, h5, h6 {
    margin-bottom: ${props => props.theme.spacing.md};
  }
`;

// ========== Animations ==========
const fadeIn = keyframes`
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
`;

const pulse = keyframes`
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.05);
  }
  100% {
    transform: scale(1);
  }
`;

const rotate = keyframes`
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
`;

// ========== Layout Components ==========
const AppContainer = styled.div`
  max-width: 1200px;
  margin: 0 auto;
  padding: ${props => props.theme.spacing.lg};
`;

const Header = styled.header`
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: ${props => props.theme.spacing.xl};
  padding-bottom: ${props => props.theme.spacing.md};
  border-bottom: 1px solid ${props => props.theme.colors.border};

  animation: ${fadeIn} 0.5s ease-out forwards;
`;

const MainTitle = styled.h1`
  color: ${props => props.theme.colors.primary};
  font-size: 28px;
  display: flex;
  align-items: center;

  &::before {
    content: "โ–ฒ";
    margin-right: ${props => props.theme.spacing.sm};
  }
`;

const Grid = styled.div`
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: ${props => props.theme.spacing.lg};
  margin-bottom: ${props => props.theme.spacing.xl};

  animation: ${fadeIn} 0.5s ease-out forwards;
  animation-delay: 0.2s;
  opacity: 0;
`;

const WideSection = styled.section`
  grid-column: 1 / -1;
  animation: ${fadeIn} 0.5s ease-out forwards;
  animation-delay: 0.4s;
  opacity: 0;
`;

// ========== Card Components ==========
const Card = styled.div`
  background-color: ${props => props.theme.colors.cardBg};
  border-radius: ${props => props.theme.borderRadius.md};
  padding: ${props => props.theme.spacing.lg};
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);

  ${props => props.interactive && `
    cursor: pointer;
    transition: all 0.3s ease;

    &:hover {
      transform: translateY(-5px);
      box-shadow: 0 8px 20px rgba(0, 0, 0, 0.3);
    }
  `}

  ${props => props.primary && `
    border-top: 4px solid ${props.theme.colors.primary};
  `}

  ${props => props.warning && `
    border-top: 4px solid ${props.theme.colors.warning};
  `}

  ${props => props.danger && `
    border-top: 4px solid ${props.theme.colors.danger};
  `}

  ${props => props.success && `
    border-top: 4px solid ${props.theme.colors.success};
  `}
`;

const CardTitle = styled.h2`
  font-size: 18px;
  display: flex;
  align-items: center;
  margin-bottom: ${props => props.theme.spacing.md};

  ${props => props.icon && `
    &::before {
      content: "${props.icon}";
      margin-right: ${props.theme.spacing.sm};
    }
  `}
`;

const CardContent = styled.div`
  margin-bottom: ${props => props.theme.spacing.md};
`;

// ========== Button Components ==========
const Button = styled.button`
  background-color: ${props =>
    props.primary ? props.theme.colors.primary :
    props.danger ? props.theme.colors.danger :
    props.success ? props.theme.colors.success :
    props.warning ? props.theme.colors.warning :
    '#95a5a6'
  };
  color: white;
  border: none;
  border-radius: ${props => props.theme.borderRadius.sm};
  padding: ${props => props.small ? '6px 12px' : '10px 20px'};
  font-family: ${props => props.theme.fonts.body};
  font-size: ${props => props.small ? '12px' : '14px'};
  font-weight: bold;
  cursor: pointer;
  transition: all 0.3s ease;

  &:hover {
    filter: brightness(1.1);
    transform: translateY(-2px);
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
  }

  &:active {
    transform: translateY(0);
  }

  ${props => props.ghost && `
    background-color: transparent;
    color: ${
      props.primary ? props.theme.colors.primary :
      props.danger ? props.theme.colors.danger :
      props.success ? props.theme.colors.success :
      props.warning ? props.theme.colors.warning :
      props.theme.colors.text
    };
    border: 1px solid currentColor;

    &:hover {
      background-color: rgba(255, 255, 255, 0.05);
    }
  `}

  ${props => props.icon && `
    display: inline-flex;
    align-items: center;

    &::before {
      content: "${props.icon}";
      margin-right: 8px;
    }
  `}

  ${props => props.block && `
    display: block;
    width: 100%;
  `}

  ${props => props.disabled && `
    opacity: 0.5;
    cursor: not-allowed;
    pointer-events: none;
  `}

  & + & {
    margin-left: ${props => props.theme.spacing.sm};
  }
`;

// ========== Data Display Components ==========
const Statistic = styled.div`
  text-align: center;
`;

const StatValue = styled.div`
  font-size: 36px;
  font-weight: bold;
  color: ${props =>
    props.primary
      ? props.theme.colors.primary
      : props.danger
      ? props.theme.colors.danger
      : props.success
      ? props.theme.colors.success
      : props.warning
      ? props.theme.colors.warning
      : props.theme.colors.text};
  margin-bottom: ${props => props.theme.spacing.xs};

  ${props => props.pulse && `
    animation: ${pulse} 2s infinite ease-in-out;
  `}
`;

const StatLabel = styled.div`
  font-size: 14px;
  color: ${props => props.theme.colors.textMuted};
  text-transform: uppercase;
`;

const ProgressBar = styled.div`
  height: 8px;
  background-color: rgba(0, 0, 0, 0.2);
  border-radius: 4px;
  overflow: hidden;
  margin-bottom: ${props => props.theme.spacing.md};

  &::after {
    content: '';
    display: block;
    height: 100%;
    width: ${props => `${props.value}%`};
    background-color: ${props =>
      props.primary
        ? props.theme.colors.primary
        : props.danger
        ? props.theme.colors.danger
        : props.success
        ? props.theme.colors.success
        : props.warning
        ? props.theme.colors.warning
        : props.theme.colors.primary};
    transition: width 0.5s ease-in-out;
  }
`;

const StatusIndicator = styled.span`
  display: inline-block;
  width: 12px;
  height: 12px;
  border-radius: 50%;
  margin-right: ${props => props.theme.spacing.sm};
  background-color: ${props =>
    props.status === 'online'
      ? props.theme.colors.success
      : props.status === 'warning'
      ? props.theme.colors.warning
      : props.status === 'critical'
      ? props.theme.colors.danger
      : props.status === 'offline'
      ? '#95a5a6'
      : props.theme.colors.info};

  ${props => props.status === 'online' && `
    box-shadow: 0 0 10px ${props.theme.colors.success};
  `}

 ${props => props.status === 'critical' && `
    animation: ${pulse} 1s infinite;
  `}
`;

// ========== Table Components ==========
const Table = styled.table`
  width: 100%;
  border-collapse: collapse;
`;

const TableHeader = styled.th`
  text-align: left;
  padding: ${props => props.theme.spacing.sm};
  border-bottom: 2px solid ${props => props.theme.colors.border};
  color: ${props => props.theme.colors.textMuted};
  font-weight: 500;
`;

const TableCell = styled.td`
  padding: ${props => props.theme.spacing.sm};
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
`;

const TableRow = styled.tr`
  transition: background-color 0.2s ease;

  &:hover {
    background-color: rgba(255, 255, 255, 0.05);
  }
`;

// ========== Loading Spinner ==========
const Spinner = styled.div`
  display: inline-block;
  width: 24px;
  height: 24px;
  border: 3px solid rgba(255, 255, 255, 0.3);
  border-radius: 50%;
  border-top-color: ${props => props.theme.colors.primary};
  animation: ${rotate} 1s linear infinite;
  margin-right: ${props => props.theme.spacing.sm};
`;

// ========== Application Component ==========
function SpaceDashboard() {
  const [systemStatus, setSystemStatus] = useState('online');
  const [fuelLevel, setFuelLevel] = useState(72);
  const [oxygenLevel, setOxygenLevel] = useState(93);
  const [alerts, setAlerts] = useState([
    { id: 1, message: "Pressure change in module C", severity: "warning", time: "10:23" },
    { id: 2, message: "Navigation update installed", severity: "info", time: "09:15" },
    { id: 3, message: "Micrometeoroid particles detected", severity: "warning", time: "07:42" },
  ]);

  const crewMembers = [
    { id: 1, name: "Alex Chen", role: "Captain", status: "Bridge", avatar: "" },
    { id: 2, name: "Maria Rodriguez", role: "Engineer", status: "Engine Room", avatar: "" },
    { id: 3, name: "Jackson Lee", role: "Navigator", status: "Bridge", avatar: "" },
    { id: 4, name: "Sophia Kim", role: "Doctor", status: "Laboratory", avatar: "" },
  ];

  const toggleSystemStatus = () => {
    setSystemStatus(systemStatus === 'online' ? 'warning' : 'online');
  };

  return (
    <ThemeProvider theme={theme}>
      <GlobalStyle />
      <AppContainer>
        <Header>
          <MainTitle>Cosmic Command Center</MainTitle>
          <div>
            <Button primary icon="โ–ฒ" onClick={toggleSystemStatus}>
              System {systemStatus === 'online' ? 'Online' : 'Warning'}
            </Button>
          </div>
        </Header>

        <Grid>
          {/* System Status Card */}
          <Card primary>
            <CardTitle icon="โ—†">System Status</CardTitle>
            <CardContent>
              <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '20px' }}>
                <div>
                  <StatusIndicator status={systemStatus} />
                  Main status: {
                    systemStatus === 'online' ? 'All systems operational' :
                    systemStatus === 'warning' ? 'Warning - check alerts' :
                    'Malfunction'
                  }
                </div>
              </div>

              <div>
                <div style={{ marginBottom: '8px', display: 'flex', justifyContent: 'space-between' }}>
                  <span>Fuel level</span>
                  <span>{fuelLevel}%</span>
                </div>
                <ProgressBar
                  value={fuelLevel}
                  warning={fuelLevel < 50}
                  danger={fuelLevel < 20}
                  success={fuelLevel >= 50}
                />

                <div style={{ marginBottom: '8px', display: 'flex', justifyContent: 'space-between' }}>
                  <span>Oxygen level</span>
                  <span>{oxygenLevel}%</span>
                </div>
                <ProgressBar
                  value={oxygenLevel}
                  warning={oxygenLevel < 70}
                  danger={oxygenLevel < 40}
                  success={oxygenLevel >= 70}
                />
              </div>
            </CardContent>
            <Button ghost primary block>Detailed statistics</Button>
          </Card>

          {/* Crew Status Card */}
          <Card success>
            <CardTitle icon="โ—†">Crew Status</CardTitle>
            <CardContent>
              <Table>
                <thead>
                  <tr>
                    <TableHeader></TableHeader>
                    <TableHeader>Name</TableHeader>
                    <TableHeader>Location</TableHeader>
                  </tr>
                </thead>
                <tbody>
                  {crewMembers.map(member => (
                    <TableRow key={member.id}>
                      <TableCell>{member.avatar}</TableCell>
                      <TableCell>
                        {member.name}
                        <div style={{ fontSize: '12px', color: theme.colors.textMuted }}>
                          {member.role}
                        </div>
                      </TableCell>
                      <TableCell>{member.status}</TableCell>
                    </TableRow>
                  ))}
                </tbody>
              </Table>
            </CardContent>
            <Button ghost success block>Manage crew</Button>
          </Card>

          {/* Statistics Card */}
          <Card>
            <CardTitle icon="โ—†">Statistics</CardTitle>
            <CardContent>
              <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                <Statistic>
                  <StatValue primary>26</StatValue>
                  <StatLabel>Days in space</StatLabel>
                </Statistic>

                <Statistic>
                  <StatValue success>97%</StatValue>
                  <StatLabel>Efficiency</StatLabel>
                </Statistic>

                <Statistic>
                  <StatValue warning pulse={fuelLevel < 30}>{fuelLevel}%</StatValue>
                  <StatLabel>Fuel level</StatLabel>
                </Statistic>
              </div>
            </CardContent>
            <Button ghost block>See more</Button>
          </Card>

          {/* Alerts Card */}
          <Card warning={alerts.length > 0}>
            <CardTitle icon="!">Alerts</CardTitle>
            <CardContent>
              {alerts.length === 0 ? (
                <div style={{ textAlign: 'center', padding: '20px 0', color: theme.colors.textMuted }}>
                  No active alerts
                </div>
              ) : (
                <div>
                  {alerts.map(alert => (
                    <div key={alert.id} style={{
                      marginBottom: '8px',
                      padding: '8px',
                      borderRadius: '4px',
                      backgroundColor: 'rgba(0, 0, 0, 0.2)'
                    }}>
                      <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                        <div>
                          <StatusIndicator status={
                            alert.severity === 'critical' ? 'critical' :
                            alert.severity === 'warning' ? 'warning' :
                            'online'
                          } />
                          {alert.message}
                        </div>
                        <div style={{ fontSize: '12px', color: theme.colors.textMuted }}>
                          {alert.time}
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </CardContent>
            <Button ghost warning block>Check all alerts</Button>
          </Card>
        </Grid>

        <WideSection>
          <Card>
            <CardTitle>Mission Control Panel</CardTitle>
            <CardContent>
              <div style={{ display: 'flex', gap: '16px', marginBottom: '20px' }}>
                <Button primary icon="โ–ฒ">Start Operation</Button>
                <Button icon="โ—†">Analyze Data</Button>
                <Button warning icon="!">Diagnostic System</Button>
                <Button danger icon="ร—">Emergency Procedure</Button>
              </div>

              <div style={{
                backgroundColor: 'rgba(0, 0, 0, 0.3)',
                padding: '16px',
                borderRadius: '8px',
                fontFamily: theme.fonts.mono,
                fontSize: '14px'
              }}>
                <div style={{ marginBottom: '8px' }}>
                  <span style={{ color: theme.colors.success }}>system$</span> Initializing main systems...
                </div>
                <div style={{ marginBottom: '8px' }}>
                  <span style={{ color: theme.colors.success }}>system$</span> Checking communication status...
                </div>
                <div style={{ marginBottom: '8px' }}>
                  <span style={{ color: theme.colors.success }}>system$</span> Connecting to satellites...
                </div>
                <div>
                  <Spinner /> Awaiting further instructions...
                </div>
              </div>
            </CardContent>
          </Card>
        </WideSection>
      </AppContainer>
    </ThemeProvider>
  );
}

export default SpaceDashboard;

Well-Designed Solution: Component Library

One of the best approaches to managing styles in larger React projects is creating your own component library:

// File: src/components/Button/Button.styles.js
import styled, { css } from 'styled-components';

// Reusable styles
const buttonSizes = {
  small: css`
    padding: 6px 12px;
    font-size: 12px;
  `,
  medium: css`
    padding: 8px 16px;
    font-size: 14px;
  `,
  large: css`
    padding: 12px 20px;
    font-size: 16px;
  `
};

const buttonVariants = {
  primary: css`
    background-color: ${props => props.theme.colors.primary};
    color: white;

    &:hover {
      background-color: ${props => props.theme.colors.primaryDark};
    }
  `,
  secondary: css`
    background-color: ${props => props.theme.colors.secondary};
    color: white;

    &:hover {
      background-color: ${props => props.theme.colors.secondaryDark};
    }
  `,
  success: css`
    background-color: ${props => props.theme.colors.success};
    color: white;

    &:hover {
      background-color: ${props => props.theme.colors.successDark};
    }
  `,
  danger: css`
    background-color: ${props => props.theme.colors.danger};
    color: white;

    &:hover {
      background-color: ${props => props.theme.colors.dangerDark};
    }
  `
};

// Main button component
export const StyledButton = styled.button`
  display: inline-flex;
  align-items: center;
  justify-content: center;
  border: none;
  border-radius: ${props => props.theme.borderRadius.sm};
  font-family: ${props => props.theme.fonts.body};
  font-weight: 600;
  cursor: pointer;
  transition: all 0.2s ease;

  // Default size
  ${buttonSizes.medium}

  // Apply selected size
  ${props => props.size && buttonSizes[props.size]}

  // Default variant
  background-color: #e0e0e0;
  color: #333;

  &:hover {
    background-color: #d5d5d5;
  }

  // Apply selected variant
  ${props => props.variant && buttonVariants[props.variant]}

  // Ghost button style
  ${props => props.ghost && css`
    background-color: transparent;
    border: 1px solid currentColor;

    &:hover {
      background-color: rgba(0, 0, 0, 0.05);
    }
  `}

  // Disabled state
  ${props => props.disabled && css`
    opacity: 0.6;
    cursor: not-allowed;
    pointer-events: none;
  `}

  // Full width button
  ${props => props.fullWidth && css`
    width: 100%;
  `}

  // Icon support
  ${props => props.iconPosition === 'left' && props.icon && css`
    svg, img {
      margin-right: 8px;
    }
  `}

  ${props => props.iconPosition === 'right' && props.icon && css`
    svg, img {
      margin-left: 8px;
    }
  `}

  // Loading state
  ${props => props.loading && css`
    position: relative;
    color: transparent;

    &::after {
      content: "";
      position: absolute;
      top: 50%;
      left: 50%;
      width: 18px;
      height: 18px;
      margin: -9px 0 0 -9px;
      border: 2px solid rgba(255, 255, 255, 0.3);
      border-radius: 50%;
      border-top-color: white;
      animation: buttonLoader 0.8s linear infinite;
    }

    @keyframes buttonLoader {
      to { transform: rotate(360deg); }
    }
  `}
`;

// File: src/components/Button/Button.jsx
import React from 'react';
import PropTypes from 'prop-types';
import { StyledButton } from './Button.styles';

const Button = ({
  children,
  variant,
  size,
  disabled,
  fullWidth,
  ghost,
  loading,
  icon,
  iconPosition = 'left',
  as,
  ...props
}) => {
  return (
    <StyledButton
      variant={variant}
      size={size}
      disabled={disabled || loading}
      fullWidth={fullWidth}
      ghost={ghost}
      loading={loading}
      icon={icon}
      iconPosition={iconPosition}
      as={as}
      {...props}
    >
      {iconPosition === 'left' && icon}
      {children}
      {iconPosition === 'right' && icon}
    </StyledButton>
  );
};

Button.propTypes = {
  children: PropTypes.node.isRequired,
  variant: PropTypes.oneOf(['primary', 'secondary', 'success', 'danger']),
  size: PropTypes.oneOf(['small', 'medium', 'large']),
  disabled: PropTypes.bool,
  fullWidth: PropTypes.bool,
  ghost: PropTypes.bool,
  loading: PropTypes.bool,
  icon: PropTypes.node,
  iconPosition: PropTypes.oneOf(['left', 'right']),
  as: PropTypes.elementType
};

export default Button;

// File: src/components/index.js
export { default as Button } from './Button/Button';
export { default as Card } from './Card/Card';
// Other exports...

// Using the component library
import { Button, Card } from './components';

function App() {
  return (
    <div>
      <Card title="Control Panel">
        <Button variant="primary" size="large">
          Start mission
        </Button>
        <Button variant="danger" ghost>
          Cancel
        </Button>
      </Card>
    </div>
  );
}

Comparison with Other Styling Approaches

ApproachAdvantagesDisadvantages
Styled Components- Real CSS in JS<br>- Style isolation<br>- Dynamic styles based on props<br>- Built-in theme support- Increases JS bundle size<br>- Learning curve for new developers<br>- Styles are rendered at runtime
CSS Modules- Local CSS scoping<br>- No runtime CSS-in-JS<br>- Familiar CSS syntax- Limited dynamic styles<br>- Harder conditional styles<br>- Requires proper tool configuration
SCSS/SASS- Powerful features (variables, mixins, etc.)<br>- Compiled during build<br>- Familiar syntax- No selector isolation<br>- Harder integration with props<br>- Requires additional tools
Tailwind CSS- Fast development<br>- No need to name classes<br>- Consistent design system- Bloated HTML classes<br>- Harder customization<br>- Steep initial learning curve

Best Practices and Limitations

Best Practices

  1. Create reusable style components - avoid repeating CSS code
  2. Use themes - centralize values for colors, spacing, fonts, etc.
  3. Avoid nesting - deep nesting can lead to performance issues
  4. Use semantic naming - component names should reflect their function
  5. Use props for variants - instead of creating separate components

Limitations and Pitfalls

  1. Performance - with a large number of styled components, it can affect rendering time
  2. Server-Side Rendering - requires special SSR configuration
  3. Learning curve - new developers must get used to the new paradigm
  4. Debugging - automatically generated class names can make debugging harder

Summary

Styled Components is a powerful tool that changes the approach to styling in React, enabling more component-based, modular, and reactive user interfaces. Thanks to the ability to write real CSS directly in components, dynamically respond to props, and easy theming, you can create flexible and easy-to-maintain UI component systems.

In the world of cosmic React exploration, Styled Components is like an advanced space suit - it combines all the necessary tools for survival while offering freedom of movement and comfort. It teaches us that logic and appearance do not have to be separate entities but can evolve together, creating a new quality of user interfaces.

Code for this lesson: App.jsx
import React, { useState } from 'react';
import styles from './SpaceStation.module.css';

// CSS Modules demonstration
function SpaceStation() {
  const [activeModule, setActiveModule] = useState(null);

  const modules = [
    { id: 1, name: 'Command Module', status: 'online', type: 'command' },
    { id: 2, name: 'Science Module', status: 'online', type: 'science' },
    { id: 3, name: 'Habitat Module', status: 'online', type: 'habitat' },
    { id: 4, name: 'Power Module', status: 'warning', type: 'power' },
    { id: 5, name: 'Docking Module', status: 'offline', type: 'docking' }
  ];

  const getStatusClass = (status) => {
    switch(status) {
      case 'online': return styles.statusOnline;
      case 'warning': return styles.statusWarning;
      case 'offline': return styles.statusOffline;
      default: return '';
    }
  };

  return (
    <div className={styles.station}>
      <header className={styles.header}>
        <h1 className={styles.title}>Orion Space Station</h1>
        <p className={styles.subtitle}>Module management system</p>
      </header>

      <div className={styles.dashboard}>
        <div className={styles.moduleList}>
          <h2 className={styles.sectionTitle}>Station modules</h2>

          {modules.map(module => (
            <div
              key={module.id}
              className={`${styles.moduleCard} ${activeModule === module.id ? styles.active : ''}`}
              onClick={() => setActiveModule(module.id)}
            >
              <div className={styles.moduleHeader}>
                <span className={styles.moduleName}>{module.name}</span>
                <span className={`${styles.status} ${getStatusClass(module.status)}`}>
                  {module.status}
                </span>
              </div>

              <div className={styles.moduleInfo}>
                <span className={styles.moduleType}>Type: {module.type}</span>
              </div>
            </div>
          ))}
        </div>

        <div className={styles.details}>
          <h2 className={styles.sectionTitle}>Details panel</h2>

          {activeModule ? (
            <div className={styles.detailsContent}>
              <p>Selected module: <strong>{modules.find(m => m.id === activeModule)?.name}</strong></p>
              <p>System status: all systems operating normally</p>

              <div className={styles.actions}>
                <button className={styles.buttonPrimary}>Diagnostics</button>
                <button className={styles.buttonSecondary}>Report</button>
              </div>
            </div>
          ) : (
            <p className={styles.placeholder}>Select a module from the list to see details</p>
          )}
        </div>
      </div>

      <footer className={styles.footer}>
        <p>CSS Modules provide local scope for CSS classes</p>
      </footer>
    </div>
  );
}

export default SpaceStation;

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. How do you pass dynamic values to styled-components based on props?

  2. 2. What is ThemeProvider used for in styled-components?

Hands-on tasks in the game

  • Horizontal ordering

    Arrange the syntax for creating a styled-component:

  • Code editor

    Styled Components - basics of creating components with styles in JavaScript

  • Vertical ordering

    Order the steps for adding dynamic styles in styled-components:

  • Code editor

    Styled Components ThemeProvider - theme system with dynamic dark/light mode switching

  • Horizontal ordering

    Arrange the correct styled-component syntax with a dynamic color:

  • Vertical ordering

    Order styling methods from weakest to strongest coupling with the component:

  1. Put in orderBasics: styled-components Syntax
  2. QuestionBasics: Dynamic Styles in styled-components
  3. Coding taskBasics: Practice: Styled Components
  4. Put in orderBasics: Dynamic Styling Process in styled-components
  5. QuestionBasics: ThemeProvider in styled-components
  6. Coding taskBasics: Practice: ThemeProvider
  7. Put in orderBasics: styled-component Syntax with Props
  8. Put in orderBasics: Advantages of CSS-in-JS

Useful articles