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

213
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 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