React - limit itemsPerPage with useState hook

0 votes
34 views
added Feb 29 in React by lcjr First Warrant Officer (11,830 points)
import React, { useState } from 'react';
import { css, jsx } from '@emotion/react';
import dummyListings from './dummyListings';

const ResultProperty = () => {
  const [startIndex, setStartIndex] = useState(0);
  const itemsPerPage = 4;

  const handleNext = () => {
    setStartIndex(prevIndex => prevIndex + itemsPerPage);
  };

  const handlePrev = () => {
    setStartIndex(prevIndex => Math.max(prevIndex - itemsPerPage, 0));
  };

  return (
    <>
      <div
        className="result_arrow"
        css={css`
          display: flex;
          align-items: center;
        `}
      >
        {startIndex > 0 && (
          <div className="result_arrow_left" onClick={handlePrev}>
            {'<'}
          </div>
        )}

        {startIndex + itemsPerPage < dummyListings.length && (
          <div className="result_arrow_right" onClick={handleNext}>
            {'>'}
          </div>
        )}
      </div>
      <div className="result_group">
        {dummyListings
          .slice(startIndex, startIndex + itemsPerPage)
          .map(listing => (
            <div className="result_listing" key={listing.id}>
              <img src={listing.img} />
              <div className="listingWrapper">
                <span className="_title">{listing.title}</span>
                <span className="_address">{listing.address}</span>
                <span className="_price">
                  <span
                    css={css`
                      position: relative;
                      bottom: 3px;
                      font-weight: 400;
                      font-size: 16px;
                      margin-right: 5px !important;
                    `}
                  >
                    RM
                  </span>
                  {listing.price}
                </span>
                <div className="_oneliner">
                  <span>{listing.ptype}</span>
                  <span>
                    {listing.sqft}
                    sqft
                  </span>
                  <span>{listing.beds}</span>
                  <span>{listing.bathroom}</span>
                </div>
              </div>
            </div>
          ))}
      </div>
    </>
  );
};

export default ResultProperty;

 

lazacode.org - Malaysia's programming knowledge sharing platform, where everyone can share their finding as reference to others.
...