I have an array with button names. I map through them and render them. I would like to add an onClick
event that would handle them.
Those buttons are filters, so onClick event should trigger a filter function, but also I would like to change the styling, to show what filter is clicked now.
This is what I have for now:
[-] A list of buttons
const STATUS = ['All procurements', 'Draft', 'Running', 'Completed'];
[-] The mapping and styling
{STATUS.map(status => (
<button
className={`flex w-full btn justify-between hover:bg-primary-300 mb-2 cursor-pointer ${
isActiveFilter ? 'hover:bg-primary-500 bg-primary-400' : '' }` }
key={status}
onClick={handleFilterClick}
value={status.toLowerCase()}
>
{status}
{isActiveFilter && <UilCheck />}
</button>
))}
[-] And the handleFilterClick
function:
const [isActiveFilter, setIsActiveFilter] = React.useState(false);
function handleFilterClick(e: React.MouseEvent<HTMLButtonElement>) {
setFilterStatus(e.currentTarget.value as FilterStatus);
setIsActiveFilter(true);
}
Now when I click on a button, this is what I get:
But ideally I would like to get only the clicked button to be active. So what am I missing?
CodePudding user response:
I think your procedure is right just you have to add some think:
const STATUS = ['All procurements', 'Draft', 'Running', 'Completed'];
const [isActiveFilter, setIsActiveFilter] = React.useState(''); // string which one is active
function handleFilterClick(v) {
setIsActiveFilter(v);
}
{STATUS.map(status => (
<button
className={`flex w-full btn justify-between hover:bg-primary-300 mb-2
cursor-pointer ${
isActiveFilter === status ? 'hover:bg-primary-500 bg-primary-400' : '' }` }
key={status}
onClick={handleFilterClick(status)}
>
{status}
{status === isActiveFilter && <UilCheck />}
</button>
))}
base on isActiveFilter value you can add active class also