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:
class Questionnaire extends React.Component {
constructor (props) {
super(props);
this.state = { selectedSection: 0 };
this.selectSection = this.selectSection.bind(this)
}
Keep everything else the same
Solution 2:
Try This
const React = require('react');
class Questionnaire extends React.Component {
constructor (props) {
super(props);
this.state = { selectedSection: 0 };
}
selectSection = function(e){
console.log(e);
}
render () {
return (
<div>
<div className='btn-group mr-2' role='group'>
<button className='btn btn-primary' onClick={this.selectSection}>A</button>
<button className='btn btn-secondary' onClick={this.selectSection}>B</button>
<button className='btn btn-secondary' onClick={this.selectSection}>C</button>
<button className='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"