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?
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).
The
slice()method returns a shallow copy of a portion of an array into a new array object selected fromstarttoend(endnot included) wherestartandendrepresent 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" />
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>
))}