In the following code, how do I pass onclick event to the callback 'handleClick':
<button id="submit" onClick={this.props.handleClick} >Submit</button>
Doing the following in the callback, shows e as undefined:
class ParentComponent extends Component{
handleClick(e){
//e is undefined
}
}
Your code will pass the event object to this.props.handleClick
, you shouldn't need to change anything here unless the scope is somewhat different (which is hard to tell as you've left the rendering code out).
Try to reproduce this snippet in your code and it should work for you. Pay attention to the this binding.
class Toggle extends React.Component {
constructor(props) {
super(props);
this.state = {isToggleOn: true};
// This binding is necessary to make `this` work in the callback
this.handleClick = this.handleClick.bind(this);
}
handleClick(e) {
console.log(e)
this.setState(prevState => ({
isToggleOn: !prevState.isToggleOn
}));
}
render() {
return (
<button onClick={this.handleClick}>
{this.state.isToggleOn ? 'ON' : 'OFF'}
</button>
);
}
}
ReactDOM.render(
<Toggle />,
document.getElementById('root')
);
body {
padding: 5px
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root">
</div>
What's happening is that the onClick prop is expecting to get a function passed in with the signature (e) => {func body}
. Which means that any function object you pass into that prop will be called with the event
object as parameter when the onClick event is triggered.