0

Any help or hint would be greatly appreciated it!!

In the onFormSubmit() I get error: Cannot read property 'state' of undefined. Why does converting the onFormSubmit to an arrow function below solve the problem? In stackoverflow, the url :Cannot read property 'state' of undefined

STATED HOW TO SOLVE THE PROBLEM: As someone already mentioned, you have to bind the method in the constructor or in the onClick as he did

What does bind the method means in simple terms?

   onFormSubmit = event => {
   event.preventDefault();
   console.log(this.state.term);

}

Why does this other way also works:

 <form onSubmit={event => this.onFormSubmit(event)} className="ui form">
            <div className="field">

SearchBar.js

                import React from 'react';

            class SearchBar extends React.Component {

               state = { term: '' };


               onFormSubmit(event) {
                event.preventDefault();
                console.log(this.state.term);
               }


                render() {
                return (
                <div className="ui segment">
                    <form onSubmit={this.onFormSubmit} className="ui form">
                    <div className="field">
                        <label>Image Search</label>
                        <input type="text" value={this.state.term} onChange={(e) => this.setState({ term: e.target.value.toUpperCase()})} />
                    </div>
                    </form>

                </div>);
                }
            }

            export default SearchBar;
jadeite1000
  • 621
  • 2
  • 11
  • 27

3 Answers3

1
  <form onSubmit={this.onFormSubmit.bind(this)} className="ui form">
1

What is happening is this is undefined in onFormSubmit function why? because onFormSubmit has not been registered as SearchBar property. to solve either bind (onclick or in the constructor) or change your function into arrow function..... why arrow functions auto binds read about that in here. And also add constructor to your class and call the super() method.

Abdirahman
  • 180
  • 1
  • 5
0

As you say, turning the method into an arrow function binds it to this instance of the component. Binding is simply giving the function a context.

Where you use this.state and this.props, for example in your render method, the this part is referring to the current instance of your component. If render wasn't automatically bound to the component instance, you would not be able to use this.

You'll see this used a lot in React class components, but you will encounter it outside of React as well, as it's just a generic way for a Javascript class instance to refer to its own properties and methods.

Flagship1442
  • 1,688
  • 2
  • 6
  • 13