Reputation: 65
export default function CreateForm() {
const dispatch = useDispatch();
const [isOpen, setIsOpen] = useState(false);
return (
<div className="display">
{UsersList.map((user) => {
return (
<div>
<h1>{user.id}</h1>
<h1> {user.Name}</h1>
<h1> {user.userName}</h1>
<button onClick={() => {
dispatch(deleteUser({ id: beauty.id }));}}>
Delete User
</button>
<button onClick={()=>{
setIsOpen(true);
}}>View in popup</button>
<Modal open={isOpen} onClose={()=>setIsOpen(false)}>
<h2> {User.Information}</h2>
</Modal>
</div>
);})}
</div>
);
}
I am new to react and redux. I try to display a list of users on the webpage and add a popup box to each user. But when I click the button "View in popup" below a user, all users' popup boxes open, but I only want to open the popup box for that user. I realize this is because I use my function setIsOpen in the map, and setIsOpen does not associate with a specific userID. But I don't know how to fix this bug.
Upvotes: 0
Views: 952
Reputation: 218798
You have a list of objects, but in state you're only tracking a single boolean value for whether or not "the modal" is open:
const [isOpen, setIsOpen] = useState(false);
So either all of them are open or all of them are closed. Instead, track an identifier indicating which modal is open. For example:
const [openModal, setOpenModal] = useState();
To update it, set the relevant id
value to that state:
<button onClick={()=>{
setOpenModal(user.id);
}}>View in popup</button>
And to use it, check if the current record matches that value:
open={openModal === user.id}
Then to close it, simply clear the value:
onClose={() => setIsOpen(undefined)}
Upvotes: 2