Back to Styled Components

Adapting Based On Props

sections/basics/adapting-based-on-props.mdx

latest1.1 KB
Original Source

import Code from '../../components/Code'

Adapting based on props

You can pass a function ("interpolations") to a styled component's template literal to adapt it based on its props.

This button component has a primary state that changes its color. When setting the <Code>$primary</Code> prop to true, we are swapping out its background and text color.

React Server Components (v6.3.0+): Dynamic interpolations incur serialization overhead in RSC. For discrete variants, prefer data attributes (e.g., &[data-primary="true"]) with static styles. See the RSC section for best practices.

react
const Button = styled.button<{ $primary?: boolean; }>`
  /* Adapt the colors based on primary prop */
  background: ${props => props.$primary ? "#BF4F74" : "white"};
  color: ${props => props.$primary ? "white" : "#BF4F74"};

  font-size: 1em;
  margin: 1em;
  padding: 0.25em 1em;
  border: 2px solid #BF4F74;
  border-radius: 3px;
`;

render(
  <div>
    <Button>Normal</Button>
    <Button $primary>Primary</Button>
  </div>
);