Adding onclick to UI material button

Viewed 814

I am trying to add an onClick eventhandler into a material ui and sometimes it is called, sometimes it is not. However, it's working fine with regular buttons

 handleClick = (event) => {
    const value = event.target.value;
    console.log(value);
    this.setState({ filtered: this.state.videos.filter(item => { 
            return item.category === value
        })
    })

<Button value="java" onClick={this.handleClick}  color="primary">Java</Button> 
<Button value="React" onClick={this.handleClick} color="primary">React</Button> 
<Button value="C#" onClick={this.handleClick}  color="primary">C#</Button> 
<Button value="javascript" onClick={this.handleClick} color="primary">JavaScript</Button> 

when I updated to console.log to get event.target, I got the result shown in the image below I found the issue, but still don't know how yo fix it. React adds two spans to the Button that have no attribute name, so when I click the button, the function gets called, but not when I click the span

enter image description here

3 Answers

You can use event.currentTarget.value instead of event.target.value.

Material-ui's Button has a nested span inside the button, so when you use event.target.value and the user clicks the span you get the span as event.target, if you'd use event.currentTarget you'd get the element that the event listener is attached to - the button.

See a working example: https://codesandbox.io/s/cocky-cookies-s5moo?file=/src/App.js

Inside your handle click, you could also do:

return (item.category === value || item.category === event.target.innerHTML)

But obviously CD..’s answer is better

Besides relying on currentTarget, you can always curry the parameter to the callback function (imagine you are not passing in static content, but maybe the index of an iteration or some dynamic values stored in an object, etc)

Example

handleClick = (value) => () => {
    console.log(value);
    this.setState({ filtered: this.state.videos.filter(item => { 
            return item.category === value
        })
    })

<Button value="java" onClick={this.handleClick('java')}  color="primary">Java</Button> 
<Button value="React" onClick={this.handleClick('React')} color="primary">React</Button> 
<Button value="C#" onClick={this.handleClick('C#')}  color="primary">C#</Button> 
<Button value="javascript" onClick={this.handleClick('javascript')} color="primary">JavaScript</Button> 
Related