skip to Main Content

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


  1. This is a type information for typescript.

    This means that a prop called $primary, having boolean type and is optional.

    Login or Signup to reply.
  2. 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 be true or false. (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.

    Login or Signup to reply.
  3. What does this code mean: <{ $primary?: boolean; }>? Because this syntax
    isn’t explained in styled component docs.

    It is actually explained in a bit of detail in the Typescript section of the API page. See specifically Using Custom Props.

    import styled from 'styled-components';
    import Header from './Header';
    
    
    const NewHeader = styled(Header)<{ customColor: string }>`
      color: ${(props) => props.customColor};
    `;
    

    Syntax/Code Breakdown

    <{ $primary?: boolean; }>
       abbbbbbbc: ddddddd
    

    This is declaring a custom prop with the following breakdown:

    • a. "$" prefix indicates a transient prop, e.g. a prop that isn’t passed to the underlying React node or rendered to the DOM element
    • ab. Prop name, e.g. customColor or $primary
    • c. Prop is optional
    • d. Prop is a boolean type
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search