React event handler not being called using jquery val () method

How to call react handler using jquery val () method?

Below is a simple react component with an input field. Whenever the value changes, the onChange event handler is triggered and the value is set to the state of the component.

  var Hello = React.createClass({

   getInitialState: function(){
     return {
        val: this.props.defVal || ""
     };
   },
   onChange: function(event){

    var newVal = event.target.value;
    console.log("changed", newVal);
    this.setState({val: newVal});

   },
   render: function() {
     return <div>
     <input id = "asd" className = "asd" value = {this.state.val} onChange = {this.onChange}/>
     Hello {this.props.name}</div>;
   }

  });

  React.render(<Hello name="World" />, document.getElementById('container'));

      

However, the onChange handler is not fired when I use the jquery val method. Like $ ('# asd'). Val ("asd");

Is there a way I can call the handler using the jquery val function?

+3


source to share


1 answer


You need:

1.Set a ref

to an input element like:

<input id="asd" className="asd" value={this.state.val}
ref={(myInput) => { this.myInput = myInput; }/>

      

... you can now refer to this.myInput.value

.

Than you can

2.run arbitrary code using another event like onBlur:

<input id="asd" className="asd" value={this.state.val}
ref={(myInput) => { this.myInput = myInput; }
onBlur={this.onBlur.bind(this)} />

      

(or new ES6 syntax for the same)



... and:

3. Create a function to handle it that uses yours ref

:

onBlur(e) {
    var newVal = this.myInput.value; // uses the ref
    console.log("changed", newVal);
    this.setState({val: newVal});
}

      

Note:

Unlike what I've read on pages that are not action specific, you cannot do:

$('#asd').val("asd").change();

      

... (There's at least one such SO answer that naively turned me on!)

0


source







All Articles