Home > database >  How to sort and render table in ReactJs properly?
How to sort and render table in ReactJs properly?

Time:03-18

Help, people :) I made the same function (sorting function) in pure JS, but after sorting, I rendered the table every time, i.e. created a new one with sorted data, but I don’t understand how to implement it in React.

How exactly do I recreate the body of the table every time I do something with the data?

 import tableData from './data';
 import React, { useEffect, useState } from 'react';
 import './App.css';

 function App() {
   let [data, setData] = useState(tableData);
   let clickOnPrice = false;

 const sortByPrice = () => {
   let sorted = data;
   if(!clickOnPrice) {
      sorted.sort((a, b) => parseInt(a.price.replace(/ /g, '')) - parseInt(b.price.replace(/ /g, '')));
      clickOnPrice = true;
   }else {
      sorted.sort((a, b) => parseInt(b.price.replace(/ /g, '')) - parseInt(a.price.replace(/ /g, '')));
      clickOnPrice = false;
   }
 }



return (
<div className='App'>
 <table>
<thead>
  <tr>
    <th>№</th>
    <th>Название</th>
    <th><button className='price_btn' onClick={() => sortByPrice()}>Цена<span className="icons descending_icon">&nbsp;↑</span></button></th>
    <th><button className='price_btn'>Количество</button></th>
    <th>В рассрочку</th>
  </tr>
</thead>
<tbody>
  {data.map((item, index) => (
    <tr key={index}>
      <td>{index   1}</td>
      <td>{item.name}</td>
      <td>{item.price}</td>
      <td>{item.count}</td>
      <td>{(item.instalment) ? '✅' : ''}</td>
    </tr>
   ))}
   </tbody>
 </table>
 </div>
 );
 }

export default App;

CodePudding user response:

You should use data state variable to store sorted data as:

const sortByPrice = () => {
      setData(data.sort((a, b) => parseInt(a.price.replace(/ /g, '')) - parseInt(b.price.replace(/ /g, ''))));   
 }

You do not need even the variable named clickOnPrice if you want to sort data only in one way (either desc or asc).

Moreover, replace

    <th><button className='price_btn' onClick={() => sortByPrice()}>Цена<span className="icons descending_icon">&nbsp;↑</span></button></th>

with

    <th><button className='price_btn' onClick={sortByPrice}>Цена<span className="icons descending_icon">&nbsp;↑</span></button></th>

  • Related