Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sort table based on a specific default column

I’m new to ReactJS. I have a table that is sorted by clicking on each column header. Here is my code:

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('');
const [isSorted, setIsSorted] = useState(false);
const [valueHeader, setValueHeader] = useState({title: "",body: ""}); //Value header state
const [sortedUsers, setSortedUsers] = useState([]);


const pageItemCount = 15
const [pageCount, setPageCount] = useState(0)
const [currentPage, setCurrentPage] = useState(1)

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 sortFn = (userA, userB) => {
  // sort logic here, it can be whatever is needed
  // sorting alphabetically by `first_name` in this case
  return userA[valueHeader.body].localeCompare(userB[valueHeader.body]) //<== Use value of culumn header
}

useEffect(() => {
    if (isSorted) {
      setSortedUsers(currentUsers.slice().sort(sortFn))
    } else {
      setSortedUsers(currentUsers)
    }
  }, [isSorted, currentUsers, valueHeader]) //<== add valueHeader to dependency

const toggleSort = (target) => {
  setIsSorted(!isSorted)
  setValueHeader({
    title: target,
    body: target == "name" ? "first_name" : "mobile_number"
  }) //<=== set state of value header
}

const changePage = (i) => {
    setCurrentPage(i)
    const startItem = ((i - 1) * pageItemCount) + 1
    setCurrentUsers(users.slice(startItem - 1, (pageItemCount * i)))
}

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' onClick={()=>toggleSort("name")}>name</th>
                        <th className='p-2' onClick={()=>toggleSort("mobile")}>mobile</th>
                    </tr>
                </thead>
                <tbody>
                    {sortedUsers.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_number}</td> 
                        </tr>
                    )}
                </tbody>
            </table>
            <Pagination className="mt-2 pb-20" dir='ltr' page={currentPage} count={pageCount} onChange={handleChange} variant="outlined" shape="rounded" />                
        </div>
    )
}

export default Table

Now, when I click on each column header, my table is sorted based on that column. I wanted to know if is it possible to have table sorted based on a specific column at first. I mean, for example, at first my table be sorted based on the name column by default (without clicking on column header or doing anything else).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

you can do it in useeffect:

useEffect(() => {
toggleSort("name");
}, [])
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading