Search code examples
javascriptreactjsweb-componentstyled-components

How to pass child DOM nodes to react styled components


I would like to make a React component MyWrapper that allows for me to wrap other child HTML/components such as

<MyWrapper>
  <div>More code here</div>
</MyWrapper>

In the Angular world, this is called transclusion. I'm not as familiar with React so I'm not sure what to search for, or if it's even possible with Styled Components.

See the example below which stylizes a header title with colors and a typeface. Note how the content "Hello World, this is [..]" is hard-coded. Surely this component would be more useful and reusable if the inner HTML could be passed to the component and it could style any text this way.

https://github.com/styled-components/styled-components#example


Solution

  • I think you are looking for this.props.children:

    class MyWrapper extend React.Component {
      render() {
        return <Wrapper>{this.props.children}</Wrapper>;
      }
    }
    

    and then you can do:

    <MyWrapper>
        <div>My code here</div>
    </MyWrapper>