0
class SearchBar extends React.Component {

  onformsubmit(event) {
    event.preventDefault();
    console.log(this.state.text);
  }

  state = { text: '' }

  render() {
    return (
      <div className="ui segment">
        <form className="ui form" onSubmit={this.onformsubmit}>
          <div className="field">
            <label>Image Search: </label>
            <input type='text'
              onChange={(e) => { this.setState({ text: e.target.value }) }} //rerendered
              value={this.state.text} // overwrite by state.text 
            />
          </div>
        </form>
      </div>
    );
  }
}

so I was trying to stop the loading of the new page whenever user press 'ENTER' so I wrote a function called onformsubmit() to prevent the default behaviour then I tried to print the state value it's showing an error "Cannot read property 'state' of undefined". I searched it I was not able to get the exact reason.

Codebling
  • 10,764
  • 2
  • 38
  • 66
deeksha
  • 11
  • 1
  • Because your `onformsubmit` changes the context and `this` belongs to the function at that point rather than the class. One of myriad reasons to use Hooks. – codemonkey Feb 07 '21 at 05:02

1 Answers1

2

Issue

this from the class component isn't bound to the onformsubmit handler function, so this.state is undefined.

Solution

Either bind this to onformsubmit in the constructor.

constructor(props) {
  super(props0;
  this.onformsubmit = this.onformsubmit.bind(this);
  ...
}

Or convert onformsubmit to an arrow function so this is bound automatically for you.

onformsubmit = (event) => {
  event.preventDefault();
  console.log(this.state.text);
}
Drew Reese
  • 165,259
  • 14
  • 153
  • 181