Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add styling to child element using Styled Components?

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.

like image 605
user1283776 Avatar asked Apr 02 '26 16:04

user1283776


1 Answers

This is because you have to pass in the component you want to style, IE:

Style a component without wrapper

const NoPrint = styled(myComponent)`
    @media print
    {    
        display: none !important;
    }
`

this will apply a custom style directly to an element without a wrapper.

Polymorphic prop

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>
)
like image 86
Mosè Raguzzini Avatar answered Apr 04 '26 06:04

Mosè Raguzzini



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!