Skip to content Skip to sidebar Skip to footer

Not Able To Display "modal" For Respective "viewmore" Button

In app.js while displaying Modal clicking 'view more' button for respective person, can see data in modal only for the last person. link:-https://codesandbox.io/s/lucid-tree-kjoim?

Solution 1:

There is a single instance of the modal in the DOM (typically managed through a react portal), so when you map each person and create a modal, the last one set wins out. You can refactor the code to render just a single Modal and set the person you want displayed in it.

/**
 * Manage modal instance
 */const [selectedPerson, setSelectedPerson] = useState({});
const openModal = person => {
  setSelectedPerson(person);
  toggleModal(true);
};
const closeModal = () => {
  setSelectedPerson({});
  toggleModal(false);
};

In the mapping on the button's onClick handler you want to call openModal to set the person and open state.

.map(person => {
  return (
    <Colsm="4"><EmployeeCardkey={person.id}person={person} /><buttononClick={() => openModal(person)}>VIEW MORE</button></Col>
  );
});

Move the Modal to end of the render function and use the selectedPerson object and closeModal callback.

<ModalisOpen={isModalOpen}toggle={toggleModal}><h1>
    NAME: {selectedPerson.firstName} {selectedPerson.lastName}
  </h1><h3>AGE: {selectedPerson.age}</h3><p>{selectedPerson.bio}</p><buttononClick={closeModal}>CLOSE</button></Modal>

Edit open/close person modal

enter image description here

Post a Comment for "Not Able To Display "modal" For Respective "viewmore" Button"