user1283776
user1283776

Reputation: 21764

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.

Upvotes: 3

Views: 3414

Answers (3)

DEMORALIZ3D
DEMORALIZ3D

Reputation: 83

Realistically you cant escape the wrapping div. You will have to either wrap it somewhere or, create a static styled component that can be included inside other styled components by referencing it.

Example

You can put this in like a style helper file

export const NoPrint = styled.div`
    @media print
    {    
        display: none !important;
    }

then you can include it in other styled components. But it will not be wrappable around other components without an associated element like a span or div.

Upvotes: -1

Mos&#232; Raguzzini
Mos&#232; Raguzzini

Reputation: 15821

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

Upvotes: 2

Alicia
Alicia

Reputation: 29

The only way I can see to figure something without having a div would be to have your media query in a css stylesheet with a classname, and pass that classname to your elements.

something like

@media print
    .noPrint{    
        display: none !important;
    }
<p class="noPrint" >Some paragraph</p>

To make an element without a div, there is React.Fragment available, but you can't style those... I don't know if

Upvotes: 0

Related Questions