onClick On Mapped Components

Good evening,

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?

sure you can do that. Any reason why you didn’t just try that in some editor like codepen and see if it worked?

1 Like

I have tried, but (and this example up here is different) what I’m doing is a little different. These are the components:

const App = () => {
     const [display, setDisplay] = useState('0')
 return (
 <div>
     <h1 id="display">{display}</h1>
     <div>{numList.map((num, id) => 
     <Numbers value={num.value} id={num.id} onClick={() => setDisplay(num.value)}/>
     )}</div>
       
     </div>
 ) 
  {/*Answer will be shown here*/}
}


const Numbers = ({value, id}) => {
  return (
  <div>
      <h1>{value}</h1>
  </div>
  )
}

This however is still not working.

onClick on the component is a prop, not an event. You have to use the prop inside the component just like you would use any other props you pass to the component.

Example
import { useState } from "react";

const numList = [
  { value: 0, id: 0 },
  { value: 1, id: 1 },
  { value: 2, id: 2 }
];

export const App = () => {
  const [display, setDisplay] = useState(0);
  return (
    <div>
      <h1 id="display">{display}</h1>
      <div>
        {numList.map((num) => (
          <Numbers
            value={num.value}
            key={num.id}
            onClick={() => setDisplay(num.value)}
          />
        ))}
      </div>
    </div>
  );
};

const Numbers = ({ value, onClick }) => {
  return (
    <div>
      <h1 onClick={onClick}>{value}</h1>
    </div>
  );
};
3 Likes

Thank you! It works :slight_smile:

1 Like