CSS-in-JS: Styled Components

Introduction CSS-in-JS allows developers to write CSS directly within JavaScript, improving component reusability and styling management in modern frameworks like React. 1. What is Styled Components? Styled Components is a popular library for CSS-in-JS, enabling dynamic styling within React components. Installation 2. Creating Styled Components Define styles within JavaScript files using the styled API. 3. […]

  • Post author:
  • Post category: CSS
  • Reading time: 35 mins read
  • Post last modified: April 3, 2025

Introduction

CSS-in-JS allows developers to write CSS directly within JavaScript, improving component reusability and styling management in modern frameworks like React.

1. What is Styled Components?

Styled Components is a popular library for CSS-in-JS, enabling dynamic styling within React components.

Installation

npm install styled-components
Bash

2. Creating Styled Components

Define styles within JavaScript files using the styled API.

import styled from 'styled-components';

const Button = styled.button`
    background: blue;
    color: white;
    padding: 10px 20px;
    border: none;
    cursor: pointer;
    &:hover {
        background: darkblue;
    }
`;

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

3. Passing Props for Dynamic Styling

Styled components allow props for conditional styling.

const Button = styled.button`
    background: ${props => props.primary ? 'blue' : 'gray'};
    color: white;
`;
<Button primary>Primary Button</Button>
JavaScript

4. Theming with Styled Components

Define a theme and use it across components.

import { ThemeProvider } from 'styled-components';

const theme = {
    primaryColor: "blue",
    secondaryColor: "gray"
};

const Button = styled.button`
    background: ${props => props.theme.primaryColor};
    color: white;
`;

function App() {
    return (
        <ThemeProvider theme={theme}>
            <Button>Theme Button</Button>
        </ThemeProvider>
    );
}
export default App;
JavaScript

Conclusion

Styled Components provide a modern way to manage styles in React applications, enhancing maintainability and scalability.

Leave a Reply