1

I dont know what it is called and whether it is possible in REACT, I would be surprised if not. I would like to make a totally generic toggle component where I can place other components inside. Something like:

<ToggleComponent>
   <div>hello</div>
   <AnotherCusomComponent></AnotherCusomComponent>
</ToggleComponent>

So I must somehow be able to tell my ToggleComponent where to render everything inside the component. Can someone guide me to an article, sample or what this subject are called in REACT.

Thomas Segato
  • 4,567
  • 11
  • 55
  • 104
  • 1
    Yes, you can. `ToggleComponent` has property called `children`. You can pass this children inside your toggle component render method: `{this.props.children}` – demkovych Jan 29 '20 at 12:42
  • Here we go: https://reactjs.org/docs/composition-vs-inheritance.html – Phobos Jan 29 '20 at 12:44

2 Answers2

0

The children, in React, refer to the generic box whose contents are unknown until they’re passed from the parent component.

<ToggleComponent>
   <div>hello</div>
   <AnotherCusomComponent></AnotherCusomComponent>
</ToggleComponent>

const ToggleComponent = (props) => {
  return (
    <div>{props.children}</div>
  )
}
demkovych
  • 7,827
  • 3
  • 19
  • 25
0

You can do this by using the prop children which contains a list of a component's children, which you can render by simply enclosing within curly braces, like so:

function ToggleComponent({ children }) {
  return <div>{children}</div>
}

function AnotherCustomComponent() {
  return <div>AnotherCustomComponent</div>
}

ReactDOM.render(<ToggleComponent>
   <div>hello</div>
   <AnotherCustomComponent></AnotherCustomComponent>
</ToggleComponent>, document.querySelector("#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>

You can read more about the special children prop in this question: What is {this.props.children} and when you should use it?

sdgluck
  • 24,894
  • 8
  • 75
  • 90