Search code examples
reactjsonclickmaterial-uibuttonclick

Why value from a Material-UI Button is not being passed to the onClick event handler?


I am trying to pass a value from a Material-UI Button when it's clicked to it's click handler, but it's always showing value of undefined. Earlier when I was using a simple button, I was getting value but not after.

const categoryChangedHandler = (e) => {
        console.log("category choosed ========= " + e.target.value);
        setCategory(e.target.value);

    };
<Button className="CategoryButton" variant="outlined" color="primary"
                                value={category}
                                onClick={e => categoryChangedHandler(e)}
                                style={{ textAlign: 'center' }}
                            >
                                {category}
                            </Button>

and I am getting the result:

category choosed ========= undefined

Solution

  • You need to use event.currentTarget.value instead of event.target.value.

    The text of a Material-UI Button is within a <span> inside a <button> element. When you click on the text, event.target will refer to the span element; whereas event.currentTarget will refer to the element with the event handler attached (i.e. the button element) that the click event bubbled up to.

    Here's a simple working example:

    import Button from "@material-ui/core/Button";
    
    export default function App() {
      return (
        <Button value="hello" onClick={(e) => console.log(e.currentTarget.value)}>
          Hello World
        </Button>
      );
    }
    

    Edit Button currentTarget

    Related answer:

    Documentation: