Reputation: 865
I have a code, i did want to render the first three. elements of a array with several elements.
How i do can do that ? My code:
function AllComponnent () {
const arr = [1,2,3,4];
const elementsPerPage = 3;
const currentPage = 0;
const itensOnPage = arr.map(() => <ul> {currentPage*elementsPerPage} </ul>
);
return (
<div>
<input/>
<button onClick={action}> Click Here </button>
<button onClick={action}> Test</button>
<h1> {itensOnPage} </h1>
</div>
)}
ReactDOM.render (
<AllComponnent/>,
document.getElementById('root'))
<div id="root"></div>
Upvotes: 0
Views: 1977
Reputation: 36
You'd probably want to try something like
<h1>
{
itemsOnPage.slice(
currentPage * elementsToRender,
(currentPage + 1) * elementsToRender
)
}
</h1>
Though it'd be best to utilize React state here. If you had a constructor in your component, what you could do is
constructor(props) {
this.state = { currentPage: 0, elementsPerPage: 3 }
this.itemsToRender = [...]
}
renderableItems() {
return this.itemsToRender.slice(
this.state.currentPage * this.state.elementsPerPage,
(this.state.currentPage + 1) * this.state.elementsPerPage
)
}
render() {
return (
<div>
{
//... other HTML
}
<h1>{ this.renderableItems() }</h1>
</div>
)
}
There are great resources to learn JSX from the guys that wrote React itself, like https://reactjs.org/docs/introducing-jsx.html.
Upvotes: 2
Reputation: 983
You can use slice
const itensOnPage = arr.slice(0, elementsPerPage)map(() => // do your logic );
Hope this works.
Upvotes: 0