0
constructor(props) {
  super(props);
  this.submitQA = this.submitQA.bind(this);
  this.onSearchChange = this.onSearchChange.bind(this);
  this.isSearched = this.isSearched.bind(this);
  this.answerSubmitted = this.answerSubmitted.bind(this);
  this.state = {
    answers: [],
    answer: '',
    searchTerm: '',
  }
}

answerSubmitted(event) {
 event.preventDefault();
 const input = event.target.querySelector('input');
 const value = input.value;
 const updatedList = this.state.answer;
 updatedList.push(value);
 this.setState({ answer: updatedList });
}



 render() {
    return (
    <div className="App">
      <div className="center">

        <form >
          Search:  <input type="text" onChange={this.onSearchChange}  /><br/>
        </form>

        <form onSubmit={this.submitQA}>
          Q & A:
          <input type="text" placeholder=" Course/Q/A"/>
          <button type="submit"> Submit </button>
        </form>
          <span>{basicFormat}</span>
      </div>

{ this.state.answers.filter(this.isSearched(this.state.searchTerm)).map(function(item) {
return (
    <div>
      <form >
        <text> {item} </text>
        <input onSubmit={this.answerSubmitted} type="text" placeholder="answer the question"/>
      </form>
    </div>
)
  }
    )
      }
      </div>
    );
  }
}

Why cant I use the function here? Error: Cannot read property 'answerSubmitted' of undefined. Not really sure why this is happening have tried searching around but all I could find is that people did not bind their method which I have done. Any help appreciated.

1 Answer 1

1

The function you pass to map changes the this context. Use an arrow function instead:

{this.state.answers.filter(this.isSearched(this.state.searchTerm)).map((item) => (
  <div>
    <form>
      <text> {item} </text>
      <input onSubmit={this.answerSubmitted} type="text" placeholder="answer the question"/>
    </form>
  </div>
))}

Arrow functions always have the same this as the context of where they were defined. Other functions, however, change their this value depending on how they are called.

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

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.