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
You could store only the selected index in state instead.
const [showAge, setShowAge] = useState(false);