EN
React - render first N elements from array
1 points
In this article, we would like to show you how to render the first N elements from the array in React.
To get the first N number of elements from an array we can use the slice()
, then we convert the array items to React elements with map()
method.
Quick solution:
xxxxxxxxxx
1
// some code here
2
let n = 3; // number of n first elements to render
3
let newArray = array.slice(0, n).map(i => {
4
return <element key={i.id} />
5
};
6
return (
7
<div>
8
{newArray}
9
</div>
10
)
11
};
Note:
Remember that each element should have a unique key - it helps React optimally manage changes in the DOM. Such a key may be, for example, the id assigned to each element.
xxxxxxxxxx
1
// Note: Uncomment import lines during working with JSX Compiler.
2
// import React from "react";
3
// import ReactDOM from "react-dom";
4
5
const App = () => {
6
const buttons = [
7
{ id: 1, text: "Button 1" },
8
{ id: 2, text: "Button 2" },
9
{ id: 3, text: "Button 3" },
10
{ id: 4, text: "Button 4" },
11
{ id: 5, text: "Button 5" }
12
];
13
14
// try to change n number
15
const n = 2;
16
const firstNElements = buttons.slice(0, n).map(({ id, text }) => {
17
return (<button key={id}>{text}</button>)
18
});
19
20
return (
21
<div>
22
<p>First {n} elements from array</p>
23
{firstNElements}
24
</div>
25
);
26
};
27
28
const root = document.querySelector('#root');
29
ReactDOM.render(<App />, root);