Home > Software engineering >  REACT - toggle active button class on click
REACT - toggle active button class on click

Time:03-02

I need 2 buttons, one for the "left" and one for the "right" side. I've made a separate component (subfolder) that i am calling in the main file. When the user clicks on certain button it has to become "active", getting the "square-round--active" class so it shows on the GUI. However currently i am having problem figuring out how to do that on 2 separate buttons, only one of them can be active at the time. In my current code the buttons just switch active from one another when any of them is clicked. How can i solve this ?

    const [isActive, setActive] = useState(false);

    const toggleClass = () => {
        setActive(!isActive);
    };

     <ul >
       <li>
          <button type="button" className={isActive ? 'square-round square-round--active square-round--min-width' : 'square-round square-round--min-width'}
          onClick={toggleClass} >Left</button>
       </li>
       <li>
          <button type="button" className={!isActive ? 'square-round square-round--active square-round--min-width' : 'square-round square-round--min-width'}
          onClick={toggleClass} >Right</button>
       </li>
     </ul>

I am making this as a placeholder for now, but later on i have to adjust the code to work with the backend, sending the users pick (left or right) as boolean value. I am adding the backend code below, if anyone has any idea how to put everything together i would truly appreciate it.

const inoAPI = new konfiguratorreact.client.api.InoAPI();

Getters:
inoAPI.getSestav().isOdpiranjeLevo(); // boolean
inoAPI.getSestav().isOdpiranjeDesno(); // boolean

Setters:
inoAPI.getSestav().setOdpiranjeDesno(callback(success, error)))
inoAPI.getSestav().setOdpiranjeLevo(callback(success, error)))


CodePudding user response:

You currently don't have any way of keeping track of which button is clicked. Something like this should work.

const ToggleComponent = ({ onToggle }) => {
  const [isActive, setActive] = useState(false);

  const toggleClass = (isLeft) => {
    onToggle(isLeft);

    if (isLeft)
      setActive(true);
    else
      setActive(false);
  };

 <ul >
   <li>
      <button type="button" className={isActive ? 'square-round square-round--active square-round--min-width' : 'square-round square-round--min-width'}
      onClick={() => toggleClass(true)} >Left</button>
   </li>
   <li>
      <button type="button" className={!isActive ? 'square-round square-round--active square-round--min-width' : 'square-round square-round--min-width'}
      onClick={() => toggleClass(false)} >Right</button>
   </li>
 </ul>
}

Parent Component

const ParentComponent = () => {
  [isActive, setIsActive] = useState(false);

  const handleToggle = (isActive) => {
    setActive(isActive);
  }

  return (
    <ToggleComponent onToggle={handleToggle} />
  );
}
  • Related