Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const STATUS = ['All procurements', 'Draft', 'Running', 'Completed'];

enter image description here

[-] 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:

enter image description here

But ideally I would like to get only the clicked button to be active.
So what am I missing?

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading