11

I have a component like this

    const Component = () => {
     return (
    <div>
       <div className="data1">
         {children}
       </div>
       <div className="data1">
         {children2}
       </div>
    </div>
)
    }

I would like to have Item1 and Item2 inside the "data1" div, and some other components inside the "data2" div. Writing the next code I only have Item1 and Item2 as children but I don't know how to pass the second children (for example Item3 and Item4)

<Component>
  <Item1/>
  <Item2/>
</Component>

I have to reuse the Component multiple times into the app so a function called children2 that returns the elements is not a good idea because they are different depending on where I use the component.

Itziar Urbieta
  • 111
  • 1
  • 1
  • 3

4 Answers4

8

The recommended way is to create custom props for each child:

const App = () => <Component child1={<Item1 />} child2={<Item2 />} />

const Component = ({child1, child2}) => {
  return (
    <div>
      <div className="data1">
        {child1}
      </div>
      <div className="data1">
        {child2}
      </div>
    </div>
  )
}

const Item1 = () => <p>Item 1</p>
const Item2 = () => <p>Item 2</p>

ReactDOM.render(<App />, 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>
macborowy
  • 1,474
  • 10
  • 13
2

I've made an StackBlitz in order for you to check a simple solution to render multiple Children been pass to a component. But to resume my solution, if you do this:

<Component>
  <Item1/>
  <Item2/>
</Component>

You could in Component.js (or wherever the Component is defined) map (this.props.children.map({})) the prop children in order to get the details of every child past to the <Component />.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Alberto Perez
  • 2,561
  • 1
  • 14
  • 21
1

You can pass multiple components as follows:

import React from 'react'

function Child (props)  {
    return (<>
        <div>{props.child1}</div>
        <div>{props.child2}</div>
          </>
    )
}

export default Child
import React from 'react'

function Parent {
    return (
        <>
        <Child
            children1={<Item1/>}
            children2={<Item2/>}
         />
         </>
     )
}

export default Parent
ahuemmer
  • 1,653
  • 9
  • 22
  • 29
Raja Asim
  • 11
  • 2
0
    till me if it work
const Component = (item1,item2) => {
         return (
        <div>
           <div className="data1">
             {item1}
           </div>
           <div className="data1">
             {item2}
           </div>
        </div>
    )
        }
    how to used it
    which item one what you want to add  as item like this <item1/>
    <Component item1={item1} item2={item2}/>
Mohammed Al-Reai
  • 2,344
  • 14
  • 18