Home > Enterprise >  Adding items to array on click Rect
Adding items to array on click Rect

Time:11-18

I am iterating through an array of objects and displaying items to the page. On button click, I would like to add the clicked item to a favourites array.

When I click on the first button multiple times the item does get added to my array multiple times. When I click on the second or third button, the item gets added but it overrides the previous items that were stored in the array. Not sure what I am doing wrong in my handleFavourites function

import React from "react";
import Tour from "./Tour";

const Tours = ({ tours }) => {
  return (
    <section>
      <div className="title">
        <h2>our tours</h2>
        <div className="underline"></div>
      </div>
      {tours.map((tour) => {
        return <Tour tour={tour} key={tour.id} />;
      })}
    </section>
  );
};

export default Tours;
import React, { useState } from "react";

const Tour = ({ tour }) => {
  const [favourites, setFavourites] = useState([]);

  const handleFavourites = () => {
    const clickedTour = {
      tour: tour.name,
    };
    setFavourites([...favourites, clickedTour]);
  };
  console.log(favourites);

  return (
    <article className="single-tour">
      <img alt={tour.name} src={tour.image} />
      <footer>
        <div className="tour-info">
          <h4>{tour.name}</h4>
          <h4 className="tour-price">${tour.price}</h4>
        </div>
        <p>{tour.info}</p>
        <button onClick={handleFavourites}>Add to favourite</button>
      </footer>
    </article>
  );
};

export default Tour;

CodePudding user response:

Each instance of your Tour component has its own independent favorites array. What you're seeing in the console is the array for the specific Tour component instance containing the clicked button.

Move the state to the parent Tours component and pass the add handler as a prop.

const Tours = ({ tours }) => {
  const [favourites, setFavourites] = useState([]);

  const handleFavourites = (tour) => {
    setFavourites([...favourites,{ tour: tour.name }]);
  };

  return (
    <section>
      <div className="title">
        <h2>our tours</h2>
        <div className="underline"></div>
      </div>
      {tours.map((tour) => {
        return (
           <Tour
             tour={tour}
             key={tour.id}
             handleFavourites={() => handleFavourites(tour)}
           />;
        )
      })}
    </section>
  );
};
  • Related