Angger Angger - 2 months ago 13
Javascript Question

react js , get siblings or parent value

I'm new to react, I'm curious how to do this properly.
suppose I have this form, by clicking button, I want to get textbox value,

var form = React.createClass({
submit : function(e){
//how to get textbox value?
},
render : function(){
return (
<form>
<input type="text" id="textbox" value="hey, get me"/>
<button onClick={this.submit}>Get it</button>
</form>
);
}
});


Any answer will be appreciated! thank you!

Answer

One way to accomplish this is using refs.

After building your component, you may find yourself wanting to "reach out" and invoke methods on component instances returned from render(). link to refs docs

Refs are basically the html elements / react instances you want to access. In this case, we want to get Input html element. We get input element by this.refs.inputValue. Then read its value by usual js rule.

 var form = React.createClass({
       submit : function(e){
          e.preventDefault();
          console.log(this.inputValue.value);
       },
       render : function(){
       return (
          <form onSubmit={this.submit}>
             <input type="text" id="textbox" defaultValue="hey, get me"
               ref={ function(node){ this.inputValue = node }.bind(this) }
             />
             <button onClick={this.submit}>Get it</button>
          </form>
          );
       }
    });

here is a jsfiddle for your example, you can check the console for the input value.

Another way to accomplish the same thing is to make your input a controlled element. That means you assign input's value attribute to this.state.inputValue and you pass a onChange event handler as onChange={yourInputHandlerFunction}.

See the answer which explains this way of accomplishing the same thing.

Comments