I have an input and a button
<input className="form-control" value={this.state.sentence} onChange={this.onChange}/>
<button type="button" onClick={this.handleSentence}></button>
I have binded both functions in constructor.
onChange(e) {this.setState({sentence: e.target.value});}
handleSentence(e) {console.log('string -->',this.state.sentence)}
on handleSentence function the log
returns Cannot read property 'state' of null
.
but in render(let{sentence}=this.state)
returns the correct value and also I see what I type in input
here is the constructor:
class SentenceForm extends Component {
constructor(props) {
super(props)
this.state = {
sentence: '',
splitedSentenceArray:[]
}
this.onChange = this.onChange.bind(this);
this.onClick = this.handleSentence.bind(this);
}
It should look like this:
<input className="form-control" value={this.state.sentence} onChange={this.onChange}/>
<button type="button" onClick={this.onClick}></button>
You bound handleSentence
method to this.onClick
. That was wrong.
The best practise is to keep the function name same when you are binding. It avoids unnecessary confusion as in your case. You had done binding of handleSentence
function by a different name but were still calling it by the same name so in your case the function was being called but since it was bound by a different name it did not refer to the correct context, where state is present.
class SentenceForm extends Component {
constructor(props) {
super(props)
this.state = {
sentence: '',
splitedSentenceArray:[]
}
this.onChange = this.onChange.bind(this);
this.handleSentence = this.handleSentence.bind(this);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With