Amir-Mousavi
Amir-Mousavi

Reputation: 4563

Cannot read property 'state' of null

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);
    }

Upvotes: 4

Views: 6033

Answers (2)

Shubham Khatri
Shubham Khatri

Reputation: 281656

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);
    }

Upvotes: 4

Piotr Sołtysiak
Piotr Sołtysiak

Reputation: 1006

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.

Upvotes: 4

Related Questions