DEV Community

Umesh Verma
Umesh Verma

Posted on

Pass Props to CSS in styled-components with typescript.

CSS styling is important to customize any react component. So styled-component is a very good library for starting.

const Container = styled.div`
  ${css`
    width: 240px;
  `}
`;
Enter fullscreen mode Exit fullscreen mode

use the above container in the React component.

return(
  <Container>
    Hello World!
  </Container>
)
Enter fullscreen mode Exit fullscreen mode

🤔 How to pass my custom width inside the container?

Thinking and Googling.......

💡 Let me create a Type definition with width prop.

type ContainerType = {
  width?: number; ///Passing Optional Props
};
Enter fullscreen mode Exit fullscreen mode

🤔 Now how can I use it in container?

const Container = styled.div<ContainerType>`
  ${css`
    width: ${(props: ContainerType) =>
      props.width !== undefined ? props.width + "px" : 240px};
  `}
`;
Enter fullscreen mode Exit fullscreen mode

Now again render in React

return(
  <Container width={300}>
    Hello World!
  </Container>
)
Enter fullscreen mode Exit fullscreen mode

🎉 It's working !!!

Many Thanks for Reading this small content.

Top comments (1)