Pass Props to CSS in styled-components with typescript.
Umesh Verma
Posted on January 15, 2021
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;
`}
`;
use the above container
in the React component.
return(
<Container>
Hello World!
</Container>
)
š¤ 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
};
š¤ Now how can I use it in container
?
const Container = styled.div<ContainerType>`
${css`
width: ${(props: ContainerType) =>
props.width !== undefined ? props.width + "px" : 240px};
`}
`;
Now again render in React
return(
<Container width={300}>
Hello World!
</Container>
)
š It's working !!!
Many Thanks for Reading this small content.
š šŖ š
š©
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.