Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot read property 'state' of null

Tags:

reactjs

jsx

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);
    }
like image 831
Amir-Mousavi Avatar asked Feb 06 '23 14:02

Amir-Mousavi


2 Answers

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.

like image 97
Piotr Sołtysiak Avatar answered Mar 09 '23 00:03

Piotr Sołtysiak


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);
    }
like image 21
Shubham Khatri Avatar answered Mar 09 '23 00:03

Shubham Khatri