React CSS-in-JS

React CSS-in-JS

CSS-in-JS is a styling approach where component styles live inside JavaScript instead of separate stylesheet files. It is commonly used with libraries like Styled Components and Emotion.

The main idea is simple: the component owns its styles, so the markup, logic, and presentation stay close together.

Styled Components Example

import styled from 'styled-components';

const Button = styled.button background: blue; color: white;; const App = () => <Button>Click me</Button>;

Why Developers Use It

Prop-Based Styling

import styled from 'styled-components';

const Alert = styled.div`
  padding: 12px 16px;
  border-radius: 8px;
  color: white;
  background: ${(props) => (props.$kind === 'success' ? '#16a34a' : '#dc2626')};
`;

function StatusMessage() {
  return <Alert $kind="success">Saved successfully</Alert>;
}

Tradeoffs

When It Makes Sense

CSS-in-JS works well when styles need to change based on props, themes, or user interaction. It is especially useful in component-heavy React apps where visual logic belongs close to the component.