Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

164
Visualizações
How to set state for each element of array

I have an array with arrays in there, and I want to display only the first 4 elements from each nested array on the first render. Then I have a showMore button which should show new 4 items from the array when clicked, but my solution affects all other elements instead of only the clicked one. Is there a way to set the slice parameters dynamically for each of those arrays? Here is the code sample of what I have tried

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

function App() {
  const [start, setStart] = useState(0);
  const [end, setEnd] = useState(4);
  const arr = [
    [1, 2, 3, 3, 4, 5, 6, 7, 8, 9],
    [1, 2, 3, 3, 4, 5, 6, 7, 8, 9],
    [1, 2, 3, 3, 4, 5, 6, 7, 8, 9],
    [1, 2, 3, 3, 4, 5, 6, 7, 8, 9],
    [1, 2, 3, 3, 4, 5, 6, 7, 8, 9]
  ];

  const mappedArr = arr.map((e) => {
    return e.slice(start, end);
  });

  const showMore = () => {
    setStart(start + end);
    setEnd(end + 4);
  };

  return (
    <div className="App">
      {mappedArr.map((e) => {
        return (
          <div>
            <span>{e}</span>
            <span onClick={showMore}>{">"}</span>
          </div>
        );
      })}
    </div>
  );
}

and the live codesandbox here How can I achieve this? Any example will be appreciated!

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Sounds like you need separate start and end for each subarray, rather than having only a single one of each for the whole component.

To make the data easier to manage, consider transforming each subarray into an object containing start and end as well as the subarray.

const initialArr = [
    [1, 2, 3, 3, 4, 5, 6, 7, 8, 9],
    [1, 2, 3, 3, 4, 5, 6, 7, 8, 9],
    [1, 2, 3, 3, 4, 5, 6, 7, 8, 9],
    [1, 2, 3, 3, 4, 5, 6, 7, 8, 9],
    [1, 2, 3, 3, 4, 5, 6, 7, 8, 9]
];
function App() {
    const [arr, setArr] = React.useState(() => initialArr.map(
        subarr => ({ start: 0, end: 4, subarr })
    ));
    const showMore = (i) => () => {
        setArr(arr.map((e, j) => j !== i ? e : ({
            ...e,
            start: e.start + 4,
            end: e.end + 4,
        })));
    };
    return (
        <div className="App">
            {arr.map((e, i) => {
                return (
                    <div>
                        <span>{e.subarr.slice(e.start, e.end)}</span>
                        <span onClick={showMore(i)}>{">"}</span>
                    </div>
                );
            })}
        </div>
    );
}

ReactDOM.render(<App />, document.querySelector('.react'));
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div class='react'></div>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda