0

I have a simple React code as shown below:

export class TodoList extends Component {

  constructor(props) {
    super(props)
    console.log(this)
  }

  addTask() {
    // why is this null 
    console.log(this.textInput)
  }



  render() {
    return (
      <div>
        <input type="text" ref={(input) => {this.textInput = input}}  />
        <button onClick={this.addTask}>Add New Task</button>

        <h6>Pending Tasks</h6>
        <PendingTaskList />

      </div>
    )
  }
}

Inside the addTask function the value of "this" is always null. I know I can fix this by binding it but my question is why is it null in the first place.

john doe
  • 9,220
  • 23
  • 91
  • 167

1 Answers1

0

It's null because this no longer refers to the class. The best way to avoid this is to use arrow function.

From the doc:

An arrow function does not create its own this context, so this has its original meaning from the enclosing context.

addTask = () => {
    console.log(this.textInput)
}
Alexandre Annic
  • 9,942
  • 5
  • 36
  • 50
  • But inside the function addTask "this" is null – john doe Jan 19 '18 at 17:31
  • It does not refer to the function, it's refers to the thing it was bound to. In this case it is unbound. You need to bind it to the instance in the constructor with `this.addTask = this.addTask.bind(this)`or use the [experimental public class fields syntax](https://babeljs.io/docs/plugins/transform-class-properties/) if you are using babel. – trixn Jan 19 '18 at 17:33
  • Why is it unbound? Usually HTML elements are bound to the window object but is this onboard because this is virtual DOM. – john doe Jan 19 '18 at 17:40
  • Ah I get it now. Class methods are not bound by default. – john doe Jan 19 '18 at 17:57