Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

162
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda