Say I want to create a styled component called <NoPrint /> that adds the following CSS to any element passed as child:
@media print
{
display: none !important;
}
How can I do that?
I want to be able to write a styled component like this:
<NoPrint><p>Some paragraph</p></NoPrint>
<NoPrint><Some>Some React component</Some></NoPrint>
I know that I can write:
const NoPrint = styled.div`
@media print
{
display: none !important;
}
`
render(
<NoPrint>
<Something />
</NoPrint>
)
But this component creates a wrapping div, which I do not want.
This is because you have to pass in the component you want to style, IE:
const NoPrint = styled(myComponent)`
@media print
{
display: none !important;
}
`
this will apply a custom style directly to an element without a wrapper.
Another way is to use a "as" polymorphic prop
const Component = styled.div`
@media print
{
display: none !important;
}
`;
render(
<Component
as="button"
onClick={() => alert('It works!')}
>
Hello World!
</Component>
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With