Ayuda, gente :) Hice la misma función (función de clasificación) en JS puro, pero después de clasificar, rendericé la tabla cada vez, es decir, creé una nueva con datos ordenados, pero no entiendo cómo implementarlo en React .
¿Cómo recreo exactamente el cuerpo de la tabla cada vez que hago algo con los datos?
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"> ↑</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;Debe usar la variable de estado de data para almacenar datos ordenados como:
const sortByPrice = () => { setData(data.sort((a, b) => parseInt(a.price.replace(/ /g, '')) - parseInt(b.price.replace(/ /g, '')))); } Ni siquiera necesita la variable llamada clickOnPrice si desea ordenar los datos solo de una manera (ya sea desc o asc).
Además, reemplaza
<th><button className='price_btn' onClick={() => sortByPrice()}>Цена<span className="icons descending_icon"> ↑</span></button></th>con
<th><button className='price_btn' onClick={sortByPrice}>Цена<span className="icons descending_icon"> ↑</span></button></th>