简体   繁体   中英

Handle multiple buttons onClick event React

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM