The DOM returned from render() is virtual, so called Virtual DOM, and we can get any factual input(value) from a virtual object, such as access to value from a component.
The ref returned from ReactDOM.render
ReactDOM.render() will return a reference to your component’s backing instance(or null for stateless components)
var myComponent = ReactDOM.render(<MyComponent />, myContainer)
However, that the JSX doesn’t return a component. It’s just a ReactElement: a lightweight representation that tells React what the mounted component should look like.
var myComponentElement = <MyComponent title = 'title'/>; //This is just a ReactElement
`</pre>
<pre>`var myComponentInstance = ReactDOM.render(myComponent, myContainer); //a Virtual DOM
`</pre>
### The ref Callback Attribute
React supports a special attribute that you can attach to any component. The 'ref' attribute ca be a callback function, and this callback will be executed **immediately after the component is mounted**. The referenced component will be passed in as a parameter, and the callback function may use the component immediately, or save the reference for future use.
It's as simple as adding a `ref` attribute to anything returned from render:
<pre>`render: function(){
return (
<TextInput ref={function(input){
if(input != nill){
input.focus();
}
}} />
);
},
`</pre>
or use ES6 arrow funciton:
<pre>`render: function(){
return <TextInput ref={(c) => this._input = c} />;
},
componentDidMount: function{
this._input.focus();
}
`</pre>
### The ref String Attribute
React also supports using a string as a ref prop on any component.
Add `ref` attribute to component so you can access to them via `this.refs`
Assign a
ref
attribute to anything returned fromrender
such as:`<input ref='myInput'> `
In some other code, access the backing instance via
this.refs
as in`var input = this.refs.myInput; var inputValue = input.value; `
A Complete Example
`var MyComponent = React.createClass({ handleClick: function(){ if(this.myTextInput != null){ this.myTextInput.focus() } }, render: function(){ return( <div> <input type='text' ref={(ref) => this.myTextInput = ref} /> <input type='button' value='Focus the text input' onClick = {this.handleClick} /> </div> ); } }); ReactDOM.render(<MyComponent />, document.getElementById('example'));
Note: ref
will be destroyed as component unmounted.