Home > Enterprise >  Make button behave like checkbox in React
Make button behave like checkbox in React

Time:09-18

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.

CodePudding user response:

You have to check the existence of reason in the array. If it exists remove it else add it to list. You always add it.

const handleSelectedValue = (values) => {
  setSelectedValues((item) => {
    let idx = item.findIndex((itm) => itm.id === values.id);
    if (idx !== -1) {
      return item.filter(itm => itm.id !== values.id)
    } else {
      return [...item, values];
    }
  });
};
  • Related