简体   繁体   中英

React js: How to sort item from API data by ascending and descending

I am fetching data from an API , which includes information about countries . I want to sort the countries by ascending and descending from onClick according their names. For now the order of name's output is in alphabetical order(AZ). I want to sort it to ZA from onClick in the name in Header component.
Any help will be appreciated.

Here isthe component I'm fetching data: useCountries


import { useState, useEffect } from 'react'

export default function useCountries(search: string) {
  const [data, setData] = useState([])
  const [savedCountries, setSavedCountries] = useState([])
  const fetchData = () => {
    fetch('https://restcountries.eu/rest/v2/all')
      .then((res) => res.json())
      .then((result) => {
        setData(result)
        setSavedCountries(result)
      })
      .catch((err) => console.log('error'))
  }
  useEffect(() => {
    const result = [...savedCountries].filter((item: any) =>
      item.name.toLowerCase().includes(search.toLowerCase())
    )
    setData(result)
  }, [search, savedCountries])

  useEffect(() => {
    fetchData()
  }, [])

  return [data]
}


Header component



import React from 'react'

import './Header.scss'

export default function Header() {
  return (
    <div className="header">
      <ul className="HeadtableRow">
        <li>Flag</li>
        <li>Name</li>  {/* onClick must work from here */}
        <li>Language</li>
        <li>Population</li>
        <li>Region</li>
      </ul>
    </div>
  )
}



In MainTable I'm mapping through fetched data


import React from 'react'

import Header from '../Header'
import TableRow from '../TableRow'

import './mainTable.scss'

export default function MainTable({ countries }: any) {
  return (
    <div>
      <Header />

      <table className="table">
        <tbody className="tableBody">
          {countries &&
            countries.map((country?: any) => (
              <TableRow
                key={country.name}
                flagUrl={country.flag}
                countryName={country.name}
                languages={country.languages}
                population={country.population}
                region={country.region}
              />
            ))}
        </tbody>
      </table>
    </div>
  )
}

Hard to give you an answer specific to your code (In your code you don't use any click handler -or- sort method). This is more a freelancer mission to give you an "as is" solution. https://stackoverflow.com/help/how-to-ask

Related Q / articles:

API

If your API support sorting you could use this => Call like /countries?sort_by=asc(name)

Hello world

"Hello World" example (I use lodash order_by method ). You could take this basic code forward (Add an active class, Use API instead of static data, handle errors, handle immutable data , and so on).

 const { useState, useEffect } = React; /* Data */ const users = [{name: "Bob", id: 1}, {name: "Abie", id: 2}, {name: "Michael", id: 3}, {name: "Zoie", id: 4}, {name: "Omer", id: 5}]; function ListItem(props) { return <li>{props.value}</li>; } function UserList(props) { const [users, setUsers] = useState(props.users); function sortUsersByAsc() { const orderBy = _.orderBy(users, ['name'], ['asc']); setUsers(orderBy); } function sortUsersByDesc() { const orderBy = _.orderBy(users, ['name'], ['desc']); setUsers(orderBy); } const listItems = users.map((user) => <ListItem key={user.id.toString()} value={user.name} /> ); return ( <div> <ul> {listItems} </ul> <button onClick={() => sortUsersByAsc()}>Sort List By <b>A to Z</b> &darr;</button> <br/><br/> <button onClick={() => sortUsersByDesc()}>Sort List By <b>Z to A</b> &uarr;</button> </div> ); } ReactDOM.render( <UserList users={users} />, document.getElementById('root') );
 button{ cursor: pointer; background: blue; color: white; }
 <div id="root"></div> <script src="https://unpkg.com/react@16/umd/react.development.js"></script> <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js"></script>

NPM package

One more idea is to use a package like ("build-in" sorting features): https://www.npmjs.com/package/react-table

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM