0

I will get error accessing the state inside onFormSubmit because when onFormSubmit was called 'this' was lost. I am not able to find out what happened in render function that made it loose the 'this' reference to our component class.

  1. I know I can resolve this by using arrow function as they take the 'this' from its surrounding environment or lexically.
  2. Can also be resolved by using bind().
      class SearchBar extends React.Component{
        state = {term:  'Hi There'};
        onFormSubmit(e){
            console.log(this.state.term)
            
        }
        render(){
            return (
                <div className="ui segment">
                   <form onSubmit={this.onFormSubmit} className="ui form">
                       <label>Image Search</label>
                       <input  type="text" value={this.state.term} onChange={(e) => {
                                                            this.setState({term: e.target.value})
                                                        }}/>
    
                   </form>
                </div>
            )
        }
    }
    
    export default SearchBar;
t.niese
  • 39,256
  • 9
  • 74
  • 101
user3847870
  • 368
  • 1
  • 6
  • 21
  • the answers to the question gave the solution but not the logic why it is happening . If you go to the link all the answers to the question are giving same solution which I pointed out in my question. I just wanted to know why it happens ? – user3847870 Jun 23 '21 at 12:43
  • 1
    `this` in Javascript can sometimes seem weird. If you have come from other languages methods usually contained `data` & `function pointer`, but in JS, the data (this), is often implied. If you try passing `obj.method`, all that gets passed is `method`,obj is lost. eg. `amethod = obj.method`,, all that amethod contains is method, data will now equal what the current this happens to be, often the global object. On the other hand if you call `obj.method`, the `this` is implied by JS looking at the `obj.method` as a whole. – Keith Jun 23 '21 at 12:59
  • but we did call this.onFormSubmit here this refers to the component ,why we still lost this? – user3847870 Jun 23 '21 at 13:01
  • 1
    Because your basically saying `onSubmit=this.onFormSubmit`, remember how I said you loose `this` when you assign to another var. So that becomes `onSubmit = onFormSubmit`, We now have no this, and `onSubmit` 's `this` will likely be `window` (global). That why we use `() => this.onFormSubmit` so that the function your passing will have captured the correct `this`. – Keith Jun 23 '21 at 13:06
  • 1
    To clarify a bit more doing `obj.someMethod()` is fine, because at the point of invocation the this (obj), can be implied. But whenever your passing `obj.someMethod` around, all that your passing is `someMethod`, obj is lost. – Keith Jun 23 '21 at 13:10

0 Answers0