Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

111
Visualizações
Sort each column of the table

I'm new to both react and Tailwind CSS. I've created a table like this in react:

import React, { useState, useEffect } from 'react'
import { getUsers } from '../../services/userService'

const Table = () => {

    const [users, setUsers] = useState([]);
    const [currentUsers, setCurrentUsers] = useState([]);
    const [search, setSearch] = useState('');

    useEffect(async () => {
    try {
        const response = await getUsers(search);
        setUsers(response.data.users);
        setPageCount(Math.ceil(response.data.users.length / pageItemCount))
        setCurrentUsers(response.data.users.slice(0, pageItemCount))
    } catch (error) { }
}, [search]);

    const handleChange = (event, value) => {
        changePage(value);
    }

    return (
        <div dir='rtl' className='bg-background mt-10 px-5 rd1200:px-30 overflow-auto'>
           
            <table className='w-full border-separate rounded-md'>
                <thead>
                    <tr className='bg-text-secondary text-white shadow-sm text-center'>
                        <th className='p-2'>name</th>
                        <th className='p-2'>mobile</th>
                    </tr>
                </thead>
                <tbody>
                    {currentUsers.map((item, index) =>
                        <tr key={item.id} className={index % 2 === 0 ? 'bg-white shadow-sm text-center' : 'bg-text bg-opacity-5 shadow-sm text-center'}>
                            <td className='text-text text-sm p-2'>{item.first_name}</td>
                            <td className='text-text text-sm p-2'>{item.mobile}</td> 
                        </tr>
                    )}
                </tbody>
            </table>
            
        </div>
    )
}

export default Table

Table columns are related (each name in the 1st column has a related mobile number in the 2nd column). I want to add an option on each column of this table, so that when I click on the header of that column, the rows become sorted (alphabetically and numerically). As an example, at first I have:

name     mobile
----     ------
Selena   236
John     123
Sam      524

When I click on the header of the 1st column (name), the table should be sorted like this:

name     mobile
----     ------
John     123
Sam      524
Selena   236

and when I click again, it should change to its initial state. Is there any way?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You would need to use Array.sort() to sort a copy of your currentUsers state, while also keeping a flag (isSorted) as a reference to know if the currently displayed values are sorted or not.

const [isSorted, setIsSorted] = useState(false);
const [sortedUsers, setSortedUsers] = useState([]);

const sortFn = (userA, userB) => {
  // sort logic here, it can be whatever is needed
  // sorting alphabetically by `first_name` in this case
  return userA.first_name.localeCompare(userB.first_name)
}

const toggleSort = () => {
  setIsSorted(!isSorted)
}

// when `currentUsers` changes we want to reset our table
// in order to keep it in sync with actual values
// we're also sorting if we were already sorting
useEffect(() => {
  if (isSorted) {
    setSortedUsers(currentUsers.slice().sort(sortFn))
  } else {
    setSortedUsers(currentUsers)
  }
}, [isSorted, currentUsers])

Finally in your jsx you would use sortedUsers to display the data instead of currentUsers, as the latter is only used as the raw source and the former is the one we applied all the logic to.

If, additionally, you would want to display an icon or text to show that the displayed values are sorted (or not), you can use isSorted for the condition.

about 4 years ago · Juan Pablo Isaza Relatório

0

Following up from the other answer. Would recommend creating a new function for the purpose of getting the sorted version of the array. You would also need to maintain a flag variable that determines if we want to show the sorted column or not that is toggled true/false when the user interacts with your column header.

const getUsers = () => {
   return isSorted ? currentUsers.slice().sort(sortFn) : currentUsers
}

In your code you would then replace the array you are currently using with a call to this function

{getUsers().map((item, index) => ....}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda