CSS-in-JS: Styled-components and Emotion
Write component styles as tagged template literals with styled-components or the css prop with Emotion, and use props for dynamic styles.
What Is CSS-in-JS?
CSS-in-JS writes component styles directly in JavaScript/TypeScript. Styles are co-located with components, support dynamic values from props, and are automatically scoped. The two most popular libraries are styled-components and Emotion.
Styled-components Basics
Use tagged template literals to define styled components. The result is a React component that renders an HTML element with the styles applied.
import styled from 'styled-components';
const Button = styled.button`
background: ${props => props.primary ? '#6366f1' : 'white'};
color: ${props => props.primary ? 'white' : '#6366f1'};
padding: 8px 16px;
border: 2px solid #6366f1;
border-radius: 4px;
cursor: pointer;
&:hover {
opacity: 0.9;
}
`;
<Button primary>Primary</Button>
<Button>Outline</Button>All lessons in this course
- BEM Methodology: Block Element Modifier
- CSS Modules: Scoped Class Names
- CSS-in-JS: Styled-components and Emotion
- Tailwind CSS Utility-First Approach