43

I'm a bit stuck with my component, I need to call onChange from props so

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

but also call another function within the component called handleChange() that updates the state.text, I tried

 <input type="text" value={this.state.text} onChange={this.props.onChange; this.handleChange} />

but this doesn't seem to work.

Ilja
  • 44,142
  • 92
  • 275
  • 498
  • 1
    Create a function, call it on change event and inside that, call 2(_or you can even call 20_) functions. – Tushar Feb 16 '16 at 14:51
  • 1
    I thought of it, but wanted to know if there is an inline sollution – Ilja Feb 16 '16 at 14:53

4 Answers4

65

You can do it by putting the two functions in double quotes:

<input type="text" value={this.state.text} onChange="this.props.onChange(); this.handleChange();" />

This should work. But it would be better if you call the second function within the first one:

function testFunction() {
    onChange();
    handleChange();
}
diiN__________
  • 7,393
  • 6
  • 42
  • 69
  • calling `this.props.onChange` doesn't seem to have any effect withing testFUnction (onChange here being simple console.log ) – Ilja Feb 16 '16 at 15:25
4

If you want inline solution, you can do something like this:

 <input type="text" value={this.state.text} onInput={this.props.onChange} onChange={this.props.handleChange} />

Difference between onInput and onChage is here:

Difference between "change" and "input" event for an `input` element

2

function(e) {this.props.onChange(e); this.handleChange(e)}.bind(this)

You might not need .bind(this), but I suspect you will.

This will create a new function on each render, so it'd be better in certain respects to have that function be a component method, but this should work.

Carl Vitullo
  • 853
  • 6
  • 15
0

in react

function handleChange1(){ console.log("call 1st function");}
function handleChange2(){ console.log("call 2nd function");}

function handleChange(){ handleChange1(); handleChange2();}

<input type="text" value={this.state.text} onChange={this.props.handleChange} />

hope you got answer.

kashif750
  • 31
  • 6
  • While this code snippet may solve the problem, it doesn't explain why or how it answers the question. Please [include an explanation for your code](//meta.stackexchange.com/q/114762/269535), as that really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. – Luca Kiebel Jan 07 '22 at 12:35