Pass Props to CSS in styled-components with typescript.

umeshiscreative

Umesh Verma

Posted on January 15, 2021

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.

šŸ’– šŸ’Ŗ šŸ™… šŸš©
umeshiscreative
Umesh Verma

Posted on January 15, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related