The data can be sorted in React component by using Javascript method sort. This method takes array as an argument and returns the sorted data based on the sorting logic provided to it. If data needs to be sorted before rendering on UI, it can be sorted in side the render method if component.
Sort data in react component
1 import React from 'react';
2 import './App.css';
3
4 class App extends React.Component {
5
6 constructor(props) {
7 super(props);
8
9 this.state = {
10 items: [
11 { name: 'first', value: 10 },
12 { name: 'second', value: 2 },
13 { name: 'third', value: 105 }
14 ]
15 }
16 }
17
18 render() {
19 return (
20 <div>
21 {}
22 {this.state.items.sort((e1, e2) => e1.value - e2.value)
23 .map((ele, index) => {
24 return <div key={index}> {ele.name} = {ele.value}</div>
25 })
26 }
27 </div>
28 );
29 }
30 }
31
32 export default App;
In the above example, Array sort method is called on items which will returns the ascending order array which is provided to map to iterate sorted array. If sorted data requires for entire component, in that case sort data before updating the state and render state data in render method.
Sort data in descending order
1 import React from 'react';
2 import './App.css';
3
4 class App extends React.Component {
5
6 constructor(props) {
7 super(props);
8
9 this.state = {
10 items: [
11 { name: 'first', value: 10 },
12 { name: 'second', value: 2 },
13 { name: 'third', value: 105 }
14 ]
15 }
16 }
17
18 render() {
19 return (
20 <div>
21 {}
22 {this.state.items.sort((e1, e2) => e2.value - e1.value)
23 .map((ele, index) => {
24 return <div key={index}> {ele.name} = {ele.value}</div>
25 })
26 }
27 </div>
28 );
29 }
30 }
31
32 export default App;
In the above examples, an array sort() method called by specifying a function that returns numbers either less then 0, if first element e1 is less than e2. It returns positive number, if first element e1 is greater than e2 and return 0, if both value is equals.
It first sorts an array and than map each elements into html element div with key that uniquely identifies each rendered element. It used when value of array element change. It identifies elements using key whose value is changed and re-rended only those element that matches with key.
Related options for your search