Array.prototype.sort()
method to sort the data and then render it using the map()
method.Here is an example of a functional component that sorts an array of objects by a specified property and renders them in a list:
import React, { useState } from 'react'; const MyComponent = (props) => { const [data, setData] = useState(props.data); const handleSort = (property) => { const sortedData = data.sort((a, b) => { if (a[property] < b[property]) { return -1; } if (a[property] > b[property]) { return 1; } return 0; }); setData(sortedData); } return ( <> <button onClick={() => handleSort('name')}>Sort by Name</button> <button onClick={() => handleSort('age')}>Sort by Age</button> <ul> {data.map((item) => ( <li key={item.id}> {item.name}, {item.age} </li> ))} </ul> </> ); } export default MyComponent;
In this example, the component accepts an array of objects as a prop and stores it in the data
state variable using the useState
hook. The component also has two buttons that allow the user to sort the data by either the name
or age
property. The handleSort
function is called when the buttons are clicked, it sorts the data array by the specified property and updates the state using the setData
function. The sorted data is then rendered in an unordered list using the map()
method.
Note that handleSort
is a simple sorting function that sorts the data based on the property passed to it. You can use any sorting algorithm you prefer or the one that fits your use case.
Social Plugin