-3

I want to add children elements in the demo element of the Wrapper component

function Wrapper() {
    return (
        <div className="demo">Something</div>
    )
}
<Wrapper>
    <span>This is something</span>
</Wrapper>

But this doesn't work! What is the correct way to do so?

4 Answers4

1

You can do that with children prop

function Wrapper({children}) {
    return (
        <div className="demo">{children}</div>
    )
}
Nilesh Patel
  • 3,193
  • 6
  • 12
0

The easy way is to call {props.children}

function Wrapper(props) {
  return (
      <div className="demo">{props.children}</div>
  )
}
ReactDOM.render(
  <Wrapper>
      <span>This is something</span>
  </Wrapper>
, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="root" ></div>

From @Soroush Chehresa's answer to What is {this.props.children} and when you should use it? say that:

this.props.children does is that it is used to display whatever you include between the opening and closing tags when invoking a component

Nguyễn Văn Phong
  • 13,506
  • 17
  • 39
  • 56
0

change your wrapper component to this:

function Wrapper({ children }) {
  return (
    <>
      <div className="demo">Something</div>
      {children}
    </>
  );
}
Taghi Khavari
  • 6,272
  • 3
  • 15
  • 32
0

As in your wrapper function just add children as argument, because wrapper function needs to consume something to provide you something, so just pass children to wrapper function that internally render your children passed as argument

function Wrapper({children}) {
    return (
        <div className="demo">{children}</div>
    )
}