Answer the question
In order to leave comments, you need to log in
How to sort using Select?
There is a task to sort cards using select and inside the underlying option.
The project is based on react.
So the question is, how to sort the cards alphabetically with the choice of the appropriate option?
Select code:
<select className="sort-select">
<option className="option-item">Популярности</option>
<option className="option-item">По цене</option>
<option className="option-item">По алфавиту</option>
</select>
const [filtered, setFiltered] = useState([])
{
"items" : [
{
"id" : 1,
"name": "Колбаски Барбекю",
"img": "ссылка на фотохост",
"pizza": true,
"drink": false,
"snacks": false,
"new": true,
"meat": true,
"spicy": true
},
{
"name": "Двойной цыпленок",
"img": "ссылка на фотохост",
"pizza": true,
"drink": false,
"snacks": false,
"new": true,
"meat": true,
"spicy": false
}, ...
Answer the question
In order to leave comments, you need to log in
Describe sorting options - property name plus its type:
const sortOptions = [
{ key: '...', type: '...' },
{ key: '...', type: '...' },
...
];
const sortFunctions = {
type1: (a, b) => ...,
type2: (a, b) => ...,
...
};
const [ sortIndex, setSortIndex ] = useState(0);
const onSortChange = e => setSortIndex(+e.target.value);
<select value={sortIndex} onChange={onSortChange}>
{sortOptions.map((n, i) => <option value={i}>{n.key}</option>)}
</select>
const sortedItems = useMemo(() => {
const { key, type } = sortOptions[sortIndex];
const f = sortFunctions[type];
return [...items].sort((a, b) => f(a[key], b[key]));
}, [ items, sortIndex, sortFunctions ]);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question