简体   繁体   中英

How could I display sections in chunks of certain length in JavaScript/react

Currently I map through an array and for each item, I show a circle

    <div className='circlesCont'>
                  {launches.map((launch, index) => (
                    <div
                      className={`${'circle'} ${
                        index === slideNumber ? 'selectedPage' : ''
                      }`}
                      key={index}
                      id={index}
                      onClick={handleCirclePageClick}
                    ></div>
                  ))}
    </div>

I am trying to make it so only chunks of 8 items are being shown at a time.

For example, items 0 to 7 , then 7-13 etc.

Can this be done with logic inside the map container?

Currently, I could just hide the items whose index is more than 8 and show the first 7, but can't come up with a way to get the required behavior.

Thanks in advance

You can use .splice to create dynamic chunks as required by you. Each of your launches array entry will contain a isVisible property based on which you choose to render it or not . I have created a sandbox for it. Here's the code for reference with comments:-

import React, { useState } from "react";
import "./styles.css";

const defaultState = [
  { name: "Hey1", isVisibile: true },
  { name: "Hey2", isVisibile: true },
  { name: "Hey3", isVisibile: true },
  { name: "Hey4", isVisibile: true },
  { name: "Hey5", isVisibile: true },
  { name: "Hey6", isVisibile: true },
  { name: "Hey7", isVisibile: true },
  { name: "Hey8", isVisibile: true },
  { name: "Hey9", isVisibile: true },
  { name: "Hey10", isVisibile: true },
  { name: "Hey11", isVisibile: true },
  { name: "Hey12", isVisibile: true },
  { name: "Hey13", isVisibile: true },
  { name: "Hey14", isVisibile: true },
  { name: "Hey15", isVisibile: true },
  { name: "Hey16", isVisibile: true },
  { name: "Hey17", isVisibile: true },
  { name: "Hey18", isVisibile: true },
  { name: "Hey19", isVisibile: true }
];

export default function App() {
  const [state, setState] = useState(defaultState);

  const handleChunk = (start, end) => {
    // Get the chunk elements by using splice on copy of state;
    const chunkElements = [...state].splice(start, end - start);
    // For chunk elements, set the isVisible to false.
    chunkElements.forEach((ele) => (ele.isVisibile = false));
    // Make again a new copy of our state.
    const newState = [...state];
    // In our new state, update the visibility of the chunk elements.
    newState.splice(start, end - start, ...chunkElements);
    setState(newState);
  };
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <ul>{state.map((ele) => ele.isVisibile && <li>{ele.name}</li>)}</ul>
      <button onClick={() => handleChunk(3, 7)}>Chunk 3-7 it!!</button>
      <button onClick={() => handleChunk(8, 12)}>Chunk 8-12 it!!</button>
    </div>
  );
}

The above is a very raw implementation. It's really upto to you how you want to handle the visibility of state items but the chunking can be achieved as stated in the function.

Codesandbox

You can use slice function to limit your map

 <div className='circlesCont'>
          {launches.slice(0,7).map((launch, index) => (
            <div
              className={`${'circle'} ${
                index === slideNumber ? 'selectedPage' : ''
              }`}
              key={index}
              id={index}
              onClick={handleCirclePageClick}
            ></div>
          ))}
        </div>

You could store the page number in a state (and the number of items to display for each page in a const)

const [launchesPageIndex, setLaunchesPageIndex] = useState(0);
const itemsByPage = 7;

Then in order to implement the pagination you should replace

{launches.map((launch, index) => (

by

{launches.slice(launchesPageIndex * itemsByPage, launchesPageIndex * itemsByPage + itemsByPage).map((launch, index) => (

and when you want to go to the next page you only have to increment launchesPageIndex

setLaunchesPageIndex(launchesPageIndex + 1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM