0

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>)
}
A G
  • 21,087
  • 11
  • 87
  • 112
  • Honestly, there's a lot wrong with this overall approach. Your best bet is probably to start over and attempt one piece at a time. Don't store the same array multiple times in state. In this case the only state value you really need is an indicator of the sort direction, which could be as simple as a boolean value called `sortAscending`. Add an `onChange` handler to the ` – David May 09 '22 at 13:23

2 Answers2

0

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

karthik rao
  • 121
  • 5
  • It is task like in online shops: sort by price to asc or desc. I am glad for your help, but it works not fine. After select i wrote: `{arraySorted.map(el =>
    {el.name}
    )}` to show object in the page. But look how it works: default value of select is `to top`. When i click `to bottom` in nothing happens, but when i click `to top` array is displays in dsc order. And then depending on the choice, quite the opposite. Can you help me with it?
    –  May 09 '22 at 14:40
0

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">
A G
  • 21,087
  • 11
  • 87
  • 112
  • Thank you very much) Last question, why it should be copy array? –  May 09 '22 at 15:10
  • Sort function will be mutating (updating the same object) state. You can read more here -https://stackoverflow.com/questions/26253351/correct-modification-of-state-arrays-in-react-js. In general we want to keep state immutate (create a new object) all the times. – A G May 09 '22 at 15:17
  • Sorry what i am asking again) What does mean 0 and 1 in select? what is it about? ? –  May 09 '22 at 19:37
  • It's the option's value. You can set to anything. It's passed to the `onChange` handler as `e.target.value`. – A G May 09 '22 at 19:59