English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

ReactJS Refs

refUsed to return a reference to the element.RefsThey should generally be avoided, but they can be very useful when we need DOM measurements or to add methods to the component.

Using Refs

The following example shows how to use a reference to clear the input field.ClearInputFunction usageref = "myInput"Search for elements, reset the state, and add focus to it after clicking the button.

App.jsx

import React from 'react';
import ReactDOM from 'react-dom';
class App extends React.Component {
   constructor(props) {
      super(props);
      this.state = {
         data: ''
      }
      this.updateState = this.updateState.bind(this);
      this.clearInput = this.clearInput.bind(this);
   };
   updateState(e) {
      this.setState({data: e.target.value});
   }
   clearInput() {
      this.setState({data: ''});
      ReactDOM.findDOMNode(this.refs.myInput).focus();
   }
   render() {
      return (
         <div>
            <input value = {this.state.data} onChange = {this.updateState} 
               ref = "myInput"></input>
            <button onClick = {this.clearInput}>CLEAR</button>
            <h4{this.state.data}</h4>
         </div>
      );
   }
}
export default App;

main.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';
ReactDOM.render(<App/, document.getElementById('app'));

Once the button is pressed, the input will be cleared and the focus will be returned.