I’m reading the styled-components
documentation but there was a thing that was not explained in the documentation, below is the code example:
const Button = styled.button<{ $primary?: boolean; }>`
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;
`;
What does this code mean: <{ $primary?: boolean; }>
? Because this syntax isn’t explained in styled component docs.
3
Answers
This is a type information for typescript.
This means that a prop called
$primary
, having boolean type and is optional.I’m not super familiar with styled-components, but the code you’re mentioning gives the button a prop called
$primary
. The: boolean
indicates that the prop is a boolean, so it could betrue
orfalse
. (If you’re not familiar with props and components in frameworks like react, check out the documentation here.) To explain in simple terms, a prop is an input for a component, like a parameter for a function. The component’s display or behavior/functionality may change in response to a prop.It is actually explained in a bit of detail in the Typescript section of the API page. See specifically Using Custom Props.
Syntax/Code Breakdown
This is declaring a custom prop with the following breakdown:
"$"
prefix indicates a transient prop, e.g. a prop that isn’t passed to the underlying React node or rendered to the DOM elementcustomColor
or$primary