import React, { useState, useEffect } from 'react';
const bands = [
{
id: 1,
price: 100,
formed_in: 1996,
},
{
id: 2,
price: 350,
formed_in: 1981,
},
{
id: 3,
price: 70,
formed_in: 1987,
},
];
function App() {
const [data, setData] = useState([]);
const [sortType, setSortType] = useState(null);
useEffect(() => {
const sortArray = (type) => {
const types = {
priceAsc: 'price',
priceDesc: 'price',
formedAsc: 'formed_in',
formedDesc: 'formed_in',
};
const sortProperty = types[type];
const sorted = [...bands].sort((a, b) => {
switch (type) {
case 'priceAsc':
return a[sortProperty] - b[sortProperty];
case 'priceDesc':
return b[sortProperty] - a[sortProperty];
case 'formedAsc':
return a[sortProperty] - b[sortProperty];
case 'formedDesc':
return b[sortProperty] - a[sortProperty];
default:
return 0;
}
});
setData(sorted);
};
sortArray(sortType);
}, [sortType]);
return (
<div className="App">
<select onChange={(e) => setSortType(e.target.value)}>
<option value="priceAsc">Price Asc</option>
<option value="priceDesc">Price Desc</option>
<option value="formedAsc">Year Asc</option>
<option value="formedDesc">Year Desc</option>
</select>
{data.map((band) => (
<div key={band.id} style={{ margin: '30px' }}>
<div>{`ID: ${band.id}`}</div>
<div>{`Price: ${band.price}`}</div>
<div>{`Year of founding: ${band.formed_in}`}</div>
</div>
))}
</div>
);
}
export default App;
const SORT = [
[ 'без сортировки' ],
[ 'цена, по возрастанию', (a, b) => a.price - b.price ],
[ 'цена, по убыванию', (a, b) => b.price - a.price ],
[ 'год создания, по возрастанию', (a, b) => a.formed_in - b.formed_in ],
[ 'год создания, по убыванию', (a, b) => b.formed_in - a.formed_in ],
];
const [ sortType, setSortType ] = useState(0);
const data = useMemo(() => {
const sortFunc = SORT[sortType][1];
return sortFunc ? [...bands].sort(sortFunc) : bands;
}, [ bands, sortType ]);
<select value={sortType} onChange={e => setSortType(e.target.value)}>
{SORT.map((n, i) => <option value={i}>{n[0]}</option>)}
</select>