Home > Back-end >  How to sort data using dropdown in React Js?
How to sort data using dropdown in React Js?

Time:12-19

I have two functional components Dropdown, DisplayData and importing both in App.js. I need to sort the record based on the selection from dropdown and DisplayData.

Dropdow.jsx

const DropDown = ()=>{
return (
    <>
    <select>
        <option value="lowtohigh">Age: Low to High </option>
        <option value="hightolow">Age: High to Low </option>
    </select>
    </>
)}
export default DropDown;

DisplayData.jsx

const DisplayData = ()=> {

const record = [
    {
        SR : 1,
        Name : 'Aakash',
        Age : 25
    },
    {
        SR : 4,
        Name : 'Zahir',
        Age : 32
    },
    {
        SR : 3,
        Name : 'Mohan',
        Age : 23
    },
    {
        SR : 2,
        Name : 'Parul',
        Age : 42
    },
    {
        SR : 9,
        Name : 'Himanshu',
        Age : 18
    },
];

return (
    <>
    <table>
        {record.map((rec,index)=>{
            return (
    
    <tr key={index}>
    <td>
     {rec.SR}
    </td>
    <td>
    {rec.Name}
    </td>
    <td>
   {rec.Age}
    </td>
</tr>
            )}) }
       
    </table>
    </>
 )}

export default DisplayData;

App.js

function App() {
return (
<div className="App">
    <DropDown />
    <DisplayData/>
</div>
);}

export default App;

How can I pass prop from Dropdown to DisplayData ? or is there something other approach. I want to keep DropDown and DisplayData in separate components.

CodePudding user response:

  1. Create some state to hold the sort criteria in App.js

    const [sortDir, setSortDir] = useState("lowtohigh");
    
  2. Allow DropDown to accept the state setter as a prop

    const DropDown = ({ setSortDir }) => (
      <select onChange={(e) => setSortDir(e.target.value)}>
        <option value="lowtohigh">Age: Low to High</option>
        <option value="hightolow">Age: High to Low</option>
      </select>
    );
    
  3. Allow DisplayData to accept the sort criteria and create a memo hook to produced the sorted results

    const record = [
      /*...*/
    ];
    
    const DisplayData = ({ sortDir }) => {
      const sortedRecords = useMemo(
        () =>
          [...record].sort((a, b) => {
            return sortDir === "lowtohigh" ? a.Age - b.Age : b.Age - a.Age;
          }),
        [sortDir]
      );
    
      return (
        <table>
          {sortedRecords.map((rec) => (
            <tr key={rec.SR}>{/* etc */}</tr>
          ))}
        </table>
      );
    };
    
  4. Pass the props into the components

    return (
      <div className="App">
        <DropDown setSortDir={setSortDir} />
        <DisplayData sortDir={sortDir} />
      </div>
    );
    
  • Related