Having Functionality on a Mapped Component

Good morning,

Is it possible to use an onClick method as a prop in a mapped component? Here is the code:

const newArr = [
  {
    name: 'John',
    age: 25
  },
  {
    name: 'Sam',
    age: 23
  }
]

const {useState} = React
const ListOfPeople = () => {
  const [display, setDisplay] = useState('')
  return (
  <div>
      <h1>{display}</h1>
      {newArr.map(person,id) => <ShowNames name={person.name} id={person.id} age={person.age} onClick ={() => setDisplay(person.age)}/>}
   </div>
  )
}
const ShowNames = ({name, age}) => {
  return (
  <div>{name} is {age} years old</div>
  )
}

As a result, I would like to see a small list of ‘x is x years old’ as well as being able to click on a child component and see its age. Am I going about this the right way?

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.