DEV Community

Umesh Verma
Umesh Verma

Posted on

9 3

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 (0)

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay