Dylan Bozarth
Dylan Bozarth

Reputation: 1694

OnClick function not working with custom button Component

I am passing the value of the button the user clicks on to an array with the following function.

 const [pizzaSize, setPizzaSize] = useState("Choose your Pizza Size");
  const [startPrice, setStartPrice] = useState(0);
  const addPizza = (e) => {
    setPizzaSize(e.target.name);
    setStartPrice(parseInt(e.target.value));
  };

I want to use a custom button component in order to have it toggle on and off, like I have already done with other buttons on the same page.

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

Finally I call the function as follows

<ButtonClickable3 name="test" value="5" onClick={(event) => addPizza(event)}></ButtonClickable3>

When I use a regular button the function works, so I am stumped as to why the custom one does not.
My custom buttons 1 and 2 are also working, but they are using a different function. I have put my full code on a codesandbox here.
I thank you in advance for your help.

Upvotes: 1

Views: 499

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370659

Your original <button has a name attribute, but the <ButtonClickable3 does not. so:

setPizzaSize(e.target.name);

fails with the ButtonClickable3. You need:

return <button
               type="button"
               name={props.name}
               value={props.value}

inside ButtonClickable3.

Upvotes: 5

Related Questions