Clean • Professional
Modern React applications often require dynamic, reusable, and scoped styling. CSS-in-JS is a popular approach that allows you to write CSS directly inside JavaScript files, keeping your styles close to the components they belong to.
Two of the most widely used libraries for CSS-in-JS are Styled Components and Emotion.
Styled Components uses tagged template literals to create React components with scoped styles.
Installation
npm install styled-components
# or
yarn add styled-components
Example:
import React from "react";
import styled from "styled-components";
// Styled button component
const Button = styled.button`
background-color: #007bff;
color: white;
padding: 10px 20px;
border-radius: 5px;
border: none;
cursor: pointer;
&:hover {
background-color: #0056b3;
}
`;
function App() {
return <Button>Click Me</Button>;
}
export default App;
styled.button creates a Button component with scoped styles.props.primary allows buttons to change style dynamically.
const Button = styled.button`
background-color: ${(props) =>
props.primary ? "#007bff" : "#6c757d"};
color: white;
padding: 10px 20px;
border-radius: 5px;
cursor: pointer;
`;
function App() {
return (
<div>
<Button primary>Primary</Button>
<Button>Secondary</Button>
</div>
);
}
ThemeProvider passes theme values to all styled components.
import { ThemeProvider } from "styled-components";
const theme = {
primaryColor: "#007bff",
secondaryColor: "#6c757d",
};
const Button = styled.button`
background-color: ${(props) => props.theme.primaryColor};
color: white;
padding: 10px 20px;
border-radius: 5px;
`;
function App() {
return (
<ThemeProvider theme={theme}>
<Button>Primary Button</Button>
</ThemeProvider>
);
}
Emotion is another popular CSS-in-JS library that supports both styled components syntax and object-based styling.
Installation
npm install @emotion/react @emotion/styled
# or
yarn add @emotion/react @emotion/styled
Example:
/** @jsxImportSource @emotion/react */
import { css } from "@emotion/react";
function App() {
const buttonStyle = css`
background-color: #007bff;
color: white;
padding: 10px 20px;
border-radius: 5px;
border: none;
cursor: pointer;
&:hover {
background-color: #0056b3;
}
`;
return <button css={buttonStyle}>Click Me</button>;
}
export default App;
Emotion also supports a Styled Components-like API:
import styled from "@emotion/styled";
const Button = styled.button`
background-color: ${(props) => (props.primary ? "#007bff" : "#6c757d")};
color: white;
padding: 10px 20px;
border-radius: 5px;
`;
function App() {
return (
<div>
<Button primary>Primary</Button>
<Button>Secondary</Button>
</div>
);
}
export default App;