Skip to content
Advertisement

How to make a button that show the next array item inside a card in gatsbyJs (React)

I’m doing a standard mapping like this; I use slice(0,1) to get only the first array item; without the slice will show all 10 categories in it own card

<div ClassName="card-div">
  {carsTypes.map((carsType, i) => (
     <div key={i}>
         <div className="car-type-title">   
            <h6>{CarsType.title}</h6>

            // The following makes a pagination number. i.e.: 1/10
            <p>{carsTypes.indexOf(carsType) + 1} / {carsTypes.length}</p>
            <button type="button">Next Car Type </button>
         </div>

          // This section map all the category names inside the card
         {strapi[carsType.id].map((cars, i) => {
            const brand = cars.brand
            return (
              <p className="cars-card-type" key={i}>
                <Link
                  to={carsType.getPath(brand)}
                  className="btn-nav rounded-3"
                >
                  {brand}
                </Link>
              </p>   
            )
          })}
        </div>
      ))}

How can create a button or a div that when users click on it; will pass the next card type (or category) from 1/10 to 2/10?

Advertisement

Answer

Fixed! No need to map all the array.

  const [showCars, setCars ]  = useState(0)

    <div">
      {carsType.map((carsType, i) => {
        if (i === showCategory) {
          return (
          <div key={i}>
           <div>
            <h6>{carsType.title}</h6>
            <p>{carsTypes.indexOf(carsType) + 1} / {carsTypes.length}</p>
          </div>
          {strapi[carsType.id].map((category, i) => {
            const brand = category.brand
            return (
              <p key={i}>
                <Link to={carsType.getPath(brand)}>
                  {name}
                </Link>
              </p>   
              )
            })}
            <div>
              <button
                type="button"
                className="btn"
                onClick={() => setcars(showCars + 1)}
              >
               Next
              </button>
            </div>
          </div>          
          )}
      })}
      </div>
    </div>
  )
}
Advertisement