javascriptcssreactjsbutton

Allowing only one active state across multiple buttons


I am trying to have 3 buttons that toggle their active state based on if the others are clicked. So if button 1 is active, button 2 and 3 should not be. My buttons are arranged in the following way.

<ButtonClickable3  name="Medium" value="10" onClick={(event) => addPizza(event)}></ButtonClickable3>
<ButtonClickable3 name="Large" value="15" onClick={(event) => addPizza(event)}></ButtonClickable3>
<ButtonClickable3 name="Extra Large" value="20" onClick={(event) => addPizza(event)}></ButtonClickable3>

And the component is this

const ButtonClickable3 = (props) => {
    const [isActive, setActive] = useState("false");
    const handleToggle = (e) => {
     setActive(!isActive);
     props.onClick(e)
     
    }; 
     return <button
               type="button"
               value={props.value}
               name={props.name}
               className={isActive ? "button btn fourth" : "button btn fourthActive"}
               onClick={handleToggle}
             >
              {props.name}
             </button>
   
   }

Currently the only thing I can accomplish is having all the buttons turn on and off together. I.E. One is clicked and they all change active state.

How am I able to make only one be active at a time? I have put my code in this codesandbox.


Solution

  • The state for the buttons needs to be moved from the ButtonClickable3 component up to the parent.

    So you would have something like

    const [selectedPizzaSize, setSelectedPizzaSize] = useState()
    

    Then pass in a selected prop to the components themselves

    <ButtonClickable3 name="Medium" value="10" selected={selectedPizzaSize === "10"} onClick={(event) => addPizza(event)}></ButtonClickable3>
    <ButtonClickable3 name="Large" value="15" selected={selectedPizzaSize === "15"} onClick={(event) => addPizza(event)}></ButtonClickable3>
    <ButtonClickable3 name="Extra Large" value="20" selected={selectedPizzaSize === "20"} onClick={(event) => addPizza(event)}></ButtonClickable3>
    

    You'll need to call setSelectedPizzaSize inside your addPizza function