I need your help. I have one js file with a code in which i have one component - Home
. In this component i am trying to take objects from array users
and sort them in ascending and descending order using select
tag and options. I am trying to do it, but i still don't manage to do in. Can you help me: how to sort this array and how to render in page this object depending on the order? Thank you very much
import React, {useState} from "react";
export let Home = () => {
const users = [
{id: 1, name: "One"},
{id: 2, name: "Two"},
{id: 3, name: "Three"}
];
const [arrayToTop] = useState(users);
const [arrayToBottom] = useState(users);
arrayToTop.sort((a,b) => {
return a.id - b.id;
})
arrayToBottom.sort((a,b) => {
return b.id - a.id;
})
return (<div>
<select>
<option value={arrayToTop}>To top</option>
<option value={arrayToBottom}>To bottom</option>
</select>
</div>)
}
CodePudding user response:
Lots of issues as pointed by David. You need to use state
to manage the users & update state
whenever sort direction is changed in the select. It's pretty straight forward. Working sample -
const {useState} = React;
function App() {
const [users, setUsers] = useState([
{ id: 1, name: "One" },
{ id: 2, name: "Two" },
{ id: 3, name: "Three" }
]);
function onSelectionChange(e) {
const sortDirection = e.target.value;
const copyArray = [...users]; // create a new array & not mutate state
copyArray.sort((a, b) => {
return sortDirection === "0" ? a.id - b.id : b.id - a.id;
});
setUsers(copyArray); //re-render
}
return (
<div className="App">
<select defaultValue={0} onChange={onSelectionChange}>
<option value={0}>Ascending</option>
<option value={1}>Descending</option>
</select>
{users.map((user) => (
<div key={user.id}>
{user.id} - {user.name}
</div>
))}
</div>
);
}
ReactDOM.render(
<App/>,
document.getElementById("react")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="react">
CodePudding user response:
To let react know the state is updated ,only sorting is not sufficient you have to use setState(), but overall code is not clear sort and shown in option ? I belive this is want you wanted.
const [order,setOrder] = useState('asc');
const [arraySorted,setarraySorted] = useState(users);
const handler = (e)=>{
setOrder(e.target.value);
const sortedarray = arraySorted.sort((a,b) => {
return order === 'asc'? (a.id - b.id): (b.id - a.id);
})
setarraySorted([...sortedarray])}
You have to create a handler for
<select onChange={handler} value={order} >
<option value='asc'>To top</option>
<option value='dsc'>To bottom</option>
</select>
so only when required you initiale rerender , and show the sorted arry in div .list,table format whaterevr you actually wanted