2

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?

Drew Reese
  • 165,259
  • 14
  • 153
  • 181
RandomDeveloper
  • 833
  • 2
  • 9
  • 31

2 Answers2

5

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" />
Drew Reese
  • 165,259
  • 14
  • 153
  • 181
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>

))}
Ryan Le
  • 7,708
  • 1
  • 13
  • 23