React: Onclick On Button Not Working
For the past hour, I have been trying to get this to work. onClick on any of the buttons is not working at all… What am I doing wrong? const React = require('react'); class Ques
Solution 1:
You need to bind the function to the component like so:
classQuestionnaireextendsReact.Component{
constructor (props) {
super(props);
this.state = { selectedSection: 0 };
this.selectSection = this.selectSection.bind(this)
}
Keep everything else the same
Solution 2:
Try This
constReact = require('react');
classQuestionnaireextendsReact.Component {
constructor (props) {
super(props);
this.state = { selectedSection: 0 };
}
selectSection = function(e){
console.log(e);
}
render () {
return (
<div><divclassName='btn-group mr-2'role='group'><buttonclassName='btn btn-primary'onClick={this.selectSection}>A</button><buttonclassName='btn btn-secondary'onClick={this.selectSection}>B</button><buttonclassName='btn btn-secondary'onClick={this.selectSection}>C</button><buttonclassName='btn btn-secondary'onClick={this.selectSection}>D</button></div></div>
);
}
}
Solution 3:
You need to bind the method to the class. Add this line to the constructor:
this.selectSection = this.selectSection.bind(this);
Post a Comment for "React: Onclick On Button Not Working"