mercredi 15 septembre 2021

Make button behave like checkbox in React

I want to make a button behave like a checkbox in React, so the button that has been selected/clicked can return its value again or can be unselected again. But I haven't found a way.

Here's my code

  const handleSelectedValue = (reason: any) => {
    setSelectedValues(item => [...item, reason]);
  };
  

  // if value selected then change style
  const checkId = (id: number) => {
    return selectedValues.map(item => item.id).includes(id);
  };

 // inside jsx
 {reasons.map(item => {
      return (
        <button
           key={item.id}
           className={`mr-2 mb-2 text-xs border-2 rounded-full font-semibold border-card-primary px-3 sm:px-5 py-2 ${checkId(item.id) ? 'text-white bg-base-primary opacity-75 border-none' : 'text-base-secondary'}`}
           onClick={() => handleSelectedValue(item)}
         >
            {item.reason}
         </button>
     );
 })}

This code works, but the selected value cannot be unselect. Thank you.




Aucun commentaire:

Enregistrer un commentaire