1

I'm trying to print instantly my input value in the render function.

In the documentation of the concept of state and lifecycle in a React component, I see the use of a constructor with a super(props) as well as this.state.

I get the error below when trying same;

Uncaught TypeError: Cannot read property 'state' of undefined

Below is my code;

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      text: ''
    };
  };

  handleChange(event) {
    this.setState({
      text: event.target.value
    });
  };

  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.state.text}.</h2>
        <input type="text" onKeyUp={this.handleChange} />
      </div>
    );
  }
}

How can I fix it?

1
  • 2
    this.handleChange=this.handleChange.bind(this) in constructor Commented Oct 24, 2016 at 17:28

4 Answers 4

3

when you call a function like that, it is called by the window, not by your react object.

To make the function be bound to your react object (and have the ability to use the setState method, you need to use this:

onKeyUp={this.handleChange.bind(this)}

this will bind it to your react object :)

Sign up to request clarification or add additional context in comments.

1 Comment

What @Burak said in the comment on your question about binding it in the constructor is also a good suggestion, especially if you will use the function anywhere else on your page. If you have bound it in the constructor, then you can simply call this.handleChange anywhere else on your page.
1

You have to bind this to your event handler like this:

<input type="text" onKeyUp={this.handleChange.bind(this)} />

Working Example: https://codepen.io/shanedaugherty/pen/ALwAzL

1 Comment

Working example isn't opening.
1

this.handleChange = this.handleChange.bind(this); You can bind it like this in constructor and it will work, as you have to bind this to your react function.

Comments

0

You use value as an attribute.

value={this.state.text}

OR

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.