Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading