Search code examples
javascriptreactjsbindonfocus

TypeError: Cannot read property 'bind' of undefined for handleFocus


For some reason I keep on getting the

TypeError: Cannot read property 'bind' of undefined,

specifically in regards to handleFocus(event), and I don't know why. I've checked my spelling, and it seems to be correct. I don't know what the issue is. Here is my code, for your reference:

class Main extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      todo: "Type in to-do item",
      todos: []
    };

    this.handleChange = this.handleChange.bind(this);
    this.handleFocus = this.handleFocus.bind(this);
    this.handleClick = this.handleClick.bind(this);
  }

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

  handleFocus(event){
    this.setState({todo: ''});
  }

  handleSubmit(event){
    const todos = this.state.todos.slice();
    this.setState({
      todos: todos.concat([
        this.todo
        ]),
      todo: '',
    });
    event.preventDefault();
  }

  render(){
    return (
      <div className = "main">
        <h1>To Do App</h1>
        <form>
          <input type = "text" value = {this.state.todo} 
            onFocus= {this.handleFocus} 
            onChange = {this.handleChange} />
          <input type = "submit" value = "Enter to-do item"
            onClick = {this.handleSubmit}/>
        </form>
        <div className = "tasks">
          <h1>Tasks</h1>
          <button type="button">Clear List</button>
          <button type="button">Reset List</button>
        </div>
      </div>
    );
  }
}

ReactDOM.render(
  <Main />,
  document.getElementById('root')
);

Solution

  • The error is not with handleFocus, error is with handleClick.

    you are trying to bind "this" to the handleClick function which do not exist.

    commenting the line solves the issue.

     // this.handleClick = this.handleClick.bind(this);
    

    or you need to define the handleClick function