Home > Software engineering >  How can I css style a child react component?
How can I css style a child react component?

Time:11-26

In simple HTML structure I can achieve it as following. I'd like to know how can I do the same with React and Styled Component.

HTML

  <div className="slider">
    <section>Content A</section>
    <section>Content B</section>
  </div>

And I can target the styling of the section like this.

.slider section {
  //some styling
};

How can I achieve the same in React with Styled Component. In this case, my slider div is a styled component and the section is a React component as following.

  <Slider>
    <SectionComponent text="Content A />
    <SectionComponent text="Content B" />
  </Slider>

This is what I tried, within the Slider CSS code block I tried styling the SectionComponent but doesn't work.

Styled Component CSS

export const Slider = styled.div`
  //some css styling

  Slider SectionComponent {
    //styling of the SectionComponent
  }
`;

CodePudding user response:

Generally speaking you don't have to componentise every element when using React and Styled Components. Typically you only want to do this to take advantage of the extra features they bring to the table.

In your case, this would be:

   <Slider>
       <section>Content A</section>
       <section>Content B</section>
   </Slider>

and thus you could style your sections using styled components like:

  const Slider = styled.div`
      section {
         //styling of the section
      }
  `;

If you did want to have the sections as components too, then you should be able to do the above still; I've added multiple forms of section to the example below. section being the HTML element, StyledSection being the styled component and SectionComponent is a functional component which returns a <section>.

Simple working example: https://codesandbox.io/s/react-fiddle-forked-5xt6p?file=/src/App.js

When working with CSS within your Styled Components, imagine that you're still working with ordinary CSS files and HTML elements. If your SectionComponent is a child of Slider and is a <section>. Then you can select it accordingly in the same manner you would CSS.

CodePudding user response:

Try to use string templates:

export const Slider = styled.div`
  //some css styling

  ${SectionComponent} {
    //styling of the SectionComponent
  }
`;

Playground

  • Related