Search code examples
javascripthtmlcssreactjsreact-dom

React JS: Unexpected use of 'event' no-restricted-globals


I am passing the nameChangedHandler method as a reference to changed property and ultimately to the person component which i have not mentioned here, but i am getting an error in the event object.

class App extends Component {

  state = {
   persons: [
    {id: 'abc', name: "Max", age: 28},
    {id:'def', name: "Suzi", age: 30},
    {id:'fgh', name: "Alex", age:33}
    ],
  otherState: 'some other value',
  showPersons: false
       }

nameChangeHandler = (event) => {

  this.setState({
    persons: [
    {name: "Max", age: 28},
    {name: event.target.value, age: 30},
    {name: "Alex", age:26}
  ]
}
  );

}

 display_persons = (
  <div>
      return <Person         
             changed={()=>this.nameChangeHandler(event)}  />
    
</div>  
 );
}

return(
<div className="App">
  {display_persons}
</div>

 );

 }
 }


export default App;

Solution

  • Because you don't define event it thinks event is a global. onChange provides event as a parameter but you have to define it.

    Try this code:

    <Person changed={(event)=>this.nameChangeHandler(event)} />
    

    Or this one:

    <Person changed={this.nameChangeHandler} />
    

    Answer to comment:

    Well its the same like () => 2 + someParameter. This won't work because in that arrow function someParameter is not known, it will give errors. the component Person has a property onChange which will propably expect just a function and passes one parameter to it which is the event of the onChange. if you pass a parameterless arrow function, like in your question, event will have no binding locally so it will ook for globals. like console from console.log is a global. So even this code will work:

    (randomName) => this.nameChangeHandler(randomName)
    

    bacause the event is bound to the parameter randomName.

    I don't know your experience so if you have trouble understanding it maybe do some further research on 'scopes', 'parameter binding' or 'React onChange'.nMaybe these will be more clear than what i wrote :)