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

214
Vistas
Slice method with condition within loop in React

I want to render 0 to 3 items if a state is false and 4 to end of array length if state is true by clicking See more

I have the following piece of code but it's erroring out:

{items
                .filter((item) => DateTime.fromISO(item.date).year === lastYear)
                **.slice(showArticles ? (4, items.length) : (0, 3))**
                .map((filteredItem) => (
                        <div>
                            <date>{filteredItem.date}</date>
                            <span>{filteredItem.article}</div>
                        </div>

                ))}
            <button
                onClick={() => {
                    showArticles;
                }}
            >
                See more
            </button>

The current slice condition is making it so nothing is rendered. How can I show my items accordingly?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You can spread an array of args into the slice method. Remember that the ending index is excluded, so if you want elements 0-3 then specify slice(0, 4).

Array.prototype.slice

The slice() method returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included) where start and end represent the index of items in that array. The original array will not be modified.

items.filter((item) => DateTime.fromISO(item.date).year === lastYear)
  .slice(...(showArticles ? [4] : [0, 4])) // 4 through the end, or 0 to 3
  .map((filteredItem) => (....

function App() {
  const [showArticles, setShowArticles] = React.useState();

  return (
    <div className="App">
      <button type="button" onClick={() => setShowArticles((s) => !s)}>
        Toggle
      </button>

      {Array.from({ length: 10 }, (_, i) => i)
        .slice(...(showArticles ? [4] : [0, 4]))
        .map((el) => (
          <li key={el}>{el}</li>
        ))}
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(
  <App />,
  rootElement
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="root" />

about 4 years ago · Juan Pablo Isaza Denunciar

0

You are having an extra () inside the slice, this should to it:

{items
  .filter((item) => DateTime.fromISO(item.date).year === lastYear)
  .slice(showArticles ? 4 : 0, showArticles ? items.length : 3)
  .map((filteredItem) => (
          <div>
              <date>{filteredItem.date}</date>
              <span>{filteredItem.article}</div>
          </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