Skip to content
Advertisement

React Modal returns last value of mapped data

Struggling with this issue with the earlier answers not utilizing map function / functional components. When I click my Card, the modal only shows the data of the last Modal:

JavaScript

Advertisement

Answer

According to your code, multiple modals will be opened and you will see the last modal.

If you have 10 products, then 10 modals will be opened.

My suggestion is that you need to define a global modal outside map function and you need to define a new state variable to represent the selected product to be rendered on the modal.

selectedInd holds the data index to be rendered on modal.

JavaScript

Then toggle function would be changed to set -1 to hide modal.

JavaScript

And move the modal outside map.

Try to use the following code pattern.

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement