Reputation: 1792
Now sure if it's because of how these functions are being due to the arrow function (as each time I use this function, the state is refreshed from my understand).
I am trying to create a class to calls a functional component that can display many buttons). In doing so I wanted to get the information if the back to parent class and do something depending on the call.
I found something really strange, where if I click off to the side of the button (far left/right edges and corners) it always works, the method is called. If you click on the center of the button it returns undefined.
I made a demo here to see it in action: https://codesandbox.io/embed/blue-field-f9hyq?fontsize=14
Here is the sample functional component and class that are incorporated in this test:
function ButtonList(props) {
const classes = useStyles();
const onClick = e => {
props.onClick(e);
};
return (
<Button
variant="contained"
className={classes.button}
name="createEvent"
onClick={e => onClick(e)}
>
Create Event
</Button>
);
}
class App extends Component {
handleClick = e => {
if (e.target.name === "createEvent") {
console.log("event clicked");
}
};
render() {
return (
<div className="row">
<ButtonList onClick={e => this.handleClick(e)} />
</div>
);
}
}
I further investigated by removing the padding, which again caused an undefined return. I cranked the padding up and the onClick worked only within the padding.
Upvotes: 1
Views: 2532
Reputation: 2391
It is because Material render a span inside a button that has no attribute name.
<button class="MuiButtonBase-root MuiButton-root MuiButton-contained MuiButton-contained" tabindex="0" type="button" name="createEvent">
<span class="MuiButton-label">
Create Event
</span>
<span class="MuiTouchRipple-root"></span>
</button>
And your click event handler has a condition on the name attribute of the element being click.
if (e.target.name === "createEvent") {
console.log("event clicked");
}
Upvotes: 1