I have a HTML select drop down list (SortBy component), after selecting an option, the component rerenders, this is not wanted, I want to see the option I selected but it keeps reseting (rerendering) to the first option. I ve tried useCallback with no luck
When A-Z or Price: Low to high is selected, I want that value retained in the HTML select box but it defaults back to Relevance
function App() {
const [items, setItems] = useState(products);
console.log(products);
const onChange = useCallback((e) => {
const { value } = e.target;
let arr = items;
switch (value) {
case ("relevance", "saleFirst"):
arr = saleItemsFirst(items, false);
break;
case "ascend":
arr = sortByName(items);
break;
case "price":
arr = sortByPrice(items);
break;
default:
arr = saleItemsFirst(items);
break;
}
setItems([...arr]);
},
[items]
);
const SortBy = useCallback(() => {
return (
<select name="filters" onChange={onChange}>
<option value="relevance">Relevance</option>
<option value="ascend">A-Z</option>
<option value="priceLow">Price: Low to high</option>
<option value="saleFirst">Sales items first</option>
</select>
);
}, [onChange]);
return (
<div className="App">
<SortBy />
<hr />
<section>
{items.map((val) => (
<div>
<span>{val.productName}</span> <div>${val.price}</div>
<hr />
</div>
))}
</section>
......