Map array using children of parent component to reference object properties (NextJS / React)

Advertisements

I am running into a little issue that I can’t seem to solve. I am trying to map an array using the JSX elements from the children of the parent component, but don’t know how to use "item" correctly from the parent component. The idea is to have a dynamic child component that I can send different styles of children that make use of the item’s properties in the child:

export default function Parent() {
  <Child array={[ { name: 'Spencer' }, { name: 'Jimmy' }, { name: 'Frank' } ]}>
    <div>{item.name}</div>
  </Child>

  <h1>Another example of sending different children to the Child component</h1>
  <Child array={[ { name: 'Spencer' }, { name: 'Jimmy' }, { name: 'Frank' } ]}>
    <h1>{item.name}</h1>
    <p>Name of player</p>
  </Child>
}

export default function Child({array, children}) {
  return (
    <div>
      {array.map((item) => {
        {children}
      })}
    </div>
  )
}  

I tried referencing the item from the map property in the parent component, but that obviously didn’t work.

>Solution :

Use a function inside Parent, and pass item into it when mapping in Child.

function Parent() {
  return (
  <Child array={[{ name: 'Spencer' }, { name: 'Jimmy' }, { name: 'Frank' }]}>
    {(item) => <div>{item.name}</div>}
  </Child>
  )
}

function Child({array, children}) {
  return (
    <div>
      {array.map((item) => children(item))}
    </div>
  )
}  

ReactDOM.render(<Parent/>, app)
<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="app"></div>

Leave a ReplyCancel reply