skip to Main Content

I have more than one button which written in array object (name, age). I would like to show only the (age) element of the clicked button

I would like to show only the (age) element of the clicked button, but it show age of all button instead

const App = () => {
  const [showAge, setShowAge] = useState(false);
  const people = [
    {
      name: "Jeje",
      age: 4,
    },
    {
      name: "Nene",
      age: 5,
    },
    {
      name: "Tom",
      age: 8,
    },
  ];
  return (
    <div>
        {people.map((person) => (
          <>
            <div onClick={() => setShowAge(!showAge)}>
              <p data-id={person.name}>{person.name}</p>
            </div>
            {showAge && <p className="px-3">{person.age}</p>}
          </>
        ))}
    </div>
  );
};

export default App;

2

Answers


  1. You could store only the selected index in state instead.

    const [idx, setIdx] = useState();
    
    {people.map((person, i) => (
      <>
        <div onClick={() => setIdx(i)}>
          <p data-id={person.name}>{person.name}</p>
        </div>
        {idx === i && <p className="px-3">{person.age}</p>}
      </>
    ))}
    
    Login or Signup to reply.
  2. const [showAge, setShowAge] = useState(false);

    <div>
      {people.map((person) => (
        <>
          <div
            onClick={() => {
              setShowAge(!showAge);
              setNameToBeShow(person.age);
            }}
          >
            <p data-id={person.name}>{person.name}</p>
          </div>
          {nameToBeShow != 0 && person.age===nameToBeShow ?  <p className="px-3">{nameToBeShow}</p> : ''}
        </>
      ))}
    </div>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search