Using Refs
Refs are used inside components to return references to real DOM elements rendered by React. So, instead of assigning an id
or class
value to elements, we can assign refs. It's easier to get references to real DOM elements using refs than id
or class
attributes.
Let's look at a basic example of how to use refs by creating a form. First, create a container element and place it inside the body
tag. Here is the code:
<div id="container9"></div>
Here is the code for the form, which uses refs:
var FormComponent = React.createClass({ clicked: function(){ console.log(this.refs.myInput.value); }, render: function(){ return ( <div> <input type="text" placeholder="Write Something" ref="myInput" /> <input type="button" value="Click to Submit" onClick={this.clicked} /> </div> ) } }) ReactDOM.render(<FormComponent />, document.getElementById("container9"));
The output of this code on the webpage is as follows...