Home > other >  My modal is not getting the info of the car i want to show
My modal is not getting the info of the car i want to show

Time:03-15

i need help on a react JS situation :

(sorry for the english, it's not my native language, hope it's clear)

i created a modal who is supposed to get the infos of a car, so i map my data, i get all the items. Then i'd like to : on click one of the item, the modal open with the informations of the car i just clicked on. but instead it keeps the same info (the last car "maped").

i tried to use the index key... or the id, but i can'y access what i want.

Any idea why ?

here my code

data.map((offer, index) => {
          // console.log("offers map ---->", offer);
          return (
            <div key={offer.id}>
              <div>
                <p>{offer.headlines.description}</p>
                
              </div>
              <div>
                <img
                  src={offer.images.small}
                  alt="picture"
                  onClick={() => {
                    setShowModal(true);
                  }}
                />
                <ModalCar
                  title={offer.headlines.description}
                  configuration={offer.carGroupInfo}
                  image={offer.images}
                  onClose={() => {
                    setShowModal(false);
                  }}
                  show={showModal}
                />
              </div>

here my modal

const ModalCar = (props) => {
  console.log("props modal---->", props);
  if (!props.show) {
    return null;
  }
  return (
    <div className="modal">
      <div className="modal-content">
        {/* <img src={image.large} alt="" /> */}
        <div className="modal-header">
          <h1 className="modal-title">{props.title}</h1>
        </div>
        <div className="modal-body">this is modal content</div>
        <div className="modal-footer">
          <button onClick={props.onClose} className="button-modal">
            Close
          </button>
        </div>
      </div>
    </div>
  );
};
export default ModalCar;

CodePudding user response:

thanks for your time, it worked perfectly !!

CodePudding user response:

can you try replacing onClick and show props with those

onClick={() => {setShowModal(offer.id)}}
show={showModal==offer.id}

Your current code makes all the modals show up together since they all rely on showModal being true, that's why we can try specifying the id of the one that should show

a better approach would be to have only one Modal component outside of your map function, then you can do something like

onClick={() => {
   setShowModal(true)
   setSelectedOffer(offer)
}}

then you can display the selected offer from state, and just re-render it by changing the state every time the user clicks on a different offer

  • Related