I am a newbie in react and I have a problem. It turns out that I make a map of an array to show some simple cards (with image and description), to this I put a button with a toggle function that shows a paragraph. My problem is that pressing a button opens and closes all the cards. I know that it has to do with the fact that a kind of key should be passed so that it knows how to distinguish each card, but I don't know how to do it and where. can you help me? Thank you very much in advance.
code :
export default function App() {
const [activado, setActivado] = useState(false)
function handleClick() {
setActivado(!activado)
}
return (
<main>
{cardsContent.map((item) => {
return (
<figure key={item.id}>
<img src={item.img} alt={item.title} />
<figcaption>{item.title}
<button onClick={handleClick}>
+
</button>
</figcaption>
{
activado &&
<p>informacion adicional</p>
}
</figure>
)
}
)}
</main>
)
}
In the state it is not enough to know if activated is true or false, you should also know which card you want to show. That's why I change it from
false
tonull
.Then I reformulate the function
handleClick
, if I pass it aid
I will set it toactivado
, if nothing happens to it, I will doactivado = null
, (this will be useful for when you want to close the card and stop showing the info)Then I had told you about the index, but the best thing would be to use it,
id
so all you do is pass it to the button's onClick functionhandleClick(id)
.Now every time you click on a card it should change the text of the paragraph, and you could add a button to close this paragraph: