Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can onChange = {this.nameHandler} invoke nameHandler = (event) =>{}

Below is code snippets that works,

State-

state = {
        name : '',
        age : ''
    }

onChangeHandler-

nameHandler = (event) =>{
        this.setState({name: event.target.value});
    }

UI-

<input type = "text" onChange = {this.nameHandler} value = {this.state.name}/>  

But why does the following not work?

State-

state = {
        name : '',
        age : ''
    }

onChangeHandler-

nameHandler = (event) =>{
        this.setState({name: event.target.value});
    }

UI-

<input type = "text" onChange = {(event) =>this.nameHandler} value = {this.state.name}/>  

Not even the following,

state = {
        name : '',
        age : ''
    }

onChangeHandler-

nameHandler(event){
        this.setState({name: event.target.value})
    }

UI-

<input type = "text" onChange = {(event) =>this.nameHandler} value = {this.state.name}/>  

I understand the reason for my question is lacking knowledge in arrow function theory.

Please share detailed reason

like image 586
Saptarshi Nandi Avatar asked Feb 27 '26 21:02

Saptarshi Nandi


2 Answers

Consider the second example

<input type = "text" onChange = {(event) =>this.nameHandler} value = {this.state.name}/> 

Here you are not calling the original function. Here is just a wrapper function which returns another function. Events handlers are not effected by the return value.

<input type = "text" onChange = {(event) =>this.nameHandler(event)} value = {this.state.name}/> 
like image 142
Maheer Ali Avatar answered Mar 01 '26 11:03

Maheer Ali


change it following to call the function onChange: this.nameHandler --> this.nameHandler()

  <input type = "text" onChange = {(event) =>this.nameHandler(event)} value = {this.state.name}/>  
like image 40
Murtaza Hussain Avatar answered Mar 01 '26 10:03

Murtaza Hussain



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!