I'm building a React component thats basically a dropdown of sorting options. When a user clicks on a sort selection, the UI will update in accordance to the user's selection. It looks like this:
I want to display the blue checkmark on the actively selected sort. I know that using states in React is the way to go but I'm having trouble binding the state to the specifically selected user sort.
This is my component SortSelection.jsx:
const SortSelection = ({
options, extraClass, handleSort,
}) => {
const [isActive, setActive] = React.useState(false);
const handleClickSort = (e) => {
const button = e.target.closest('button');
if (button) {
const sort = button.getAttribute('data-sort');
if (button.classList.contains('selectionDropdown_menu--children-sort') && sort) {
setActive(!isActive);
}
}
};
return (
<div className={classList}>
SORT BY: {currentSortDisplayName}
<ul className="selectionDropdown_menu">
{options.map((option, index) => <li key={index} value={option.value} className="selectionDropdown_menu--children">
<Check width="20" height="20"/>
<Button text={option.name} className={`selectionDropdown_menu--children-sort ${isActive ? 'active' : null}`} onClickFunc={handleClickSort.bind(this)} data-sort={option.value} data-name={option.name}/>
</li>)}
</ul>
</div>
);
};
Unfortunately, when I update the state with setActive hook, both components get the 'active' class instead of the actual sort that the user clicked on. My idea is to show/hide the blue checkmarks(Check component) with CSS by checking the existence of the 'active' class.
How can I fix this to grab only the user's actual selected sort, in order to display the blue checkmark? I also need to ensure that on page load, the default sort of Newest will be shown, so I have to show the correct blue checkmark on page load.