Labs ICT
Pro Login

Styled Components

Styled Components

Styled Components is a CSS-in-JS library that lets you write actual CSS inside your JavaScript components. It's a popular choice for React applications, including Next.js.

Think of Styled Components as a way to create custom HTML elements with their own built-in styles. Each component carries its styles with it, making it self-contained and portable.

Setting Up Styled Components

First, install the required packages:

npm install styled-components

Then, configure Next.js to handle server-side rendering with styled-components:

// app/layout.js
'use client';

import { StyledComponentsRegistry } from './lib/registry';

export default function RootLayout({ children }) {
  return (
    <html>
      <body>
        <StyledComponentsRegistry>
          {children}
        </StyledComponentsRegistry>
      </body>
    </html>
  );
}

This setup ensures styles are properly server-rendered and avoid flash of unstyled content.

Creating Styled Components

You create styled components by calling the styled function with an HTML element or component:

import styled from 'styled-components';

const Button = styled.button`
  background-color: ${props => props.primary ? '#0070f3' : '#666'};
  color: white;
  padding: 10px 20px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  
  &:hover {
    opacity: 0.9;
  }
`;

const Container = styled.div`
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
`;

export default function App() {
  return (
    <Container>
      <Button primary>Click Me</Button>
      <Button>Cancel</Button>
    </Container>
  );
}

Notice how you can use props to dynamically change styles. The primary prop determines the button color.

Dynamic Styles

Styled Components excel at dynamic styling based on props:

const Input = styled.input`
  padding: 10px;
  border: 2px solid ${props => props.error ? '#ff0000' : '#ccc'};
  border-radius: 4px;
  font-size: 16px;
  
  &:focus {
    outline: none;
    border-color: ${props => props.error ? '#ff0000' : '#0070f3'};
  }
`;

export default function Form() {
  return (
    <div>
      <Input error placeholder="Invalid input" />
      <Input placeholder="Valid input" />
    </div>
  );
}

This creates flexible components that adapt their appearance based on the data they receive.

Global Styles with Styled Components

You can also use Styled Components for global styles using the createGlobalStyle function:

import { createGlobalStyle } from 'styled-components';

const GlobalStyle = createGlobalStyle`
  * {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
  }
  
  body {
    font-family: -apple-system, BlinkMacSystemFont, sans-serif;
    background-color: #f5f5f5;
  }
`;

export default function RootLayout({ children }) {
  return (
    <>
      <GlobalStyle />
      {children}
    </>
  );
}

This provides the same benefits as traditional global CSS but with the power of JavaScript.