traintocode

Styled Components

Styled-components, a popular library for styling React components, can be seamlessly integrated with TypeScript. By default, styled-components infer types from the styled HTML elements. However, you can explicitly define types for props passed to styled components.

For instance, if you have a styled button and want to pass a 'primary' boolean prop to alter its style, you can define a type for the prop:

type ButtonProps = {
  primary: boolean;
}

const StyledButton = styled.button<ButtonProps>`
  background-color: ${(props) => (props.primary ? 'blue' : 'gray')};
  color: white;
`;

This approach ensures that only the specified types are passed to your styled components, catching potential issues at compile-time rather than runtime.

Exercise
Add two props to the StyledDiv styled component for bgColor and fontSize. Use these two props to defined the style values.

Ask me for help or clarification:

    You cannot do the coding exercises on this device, visit this page on a larger screen.
    App.tsx
    Loading...