Home >>ReactJS Tutorial >ReactJS Refs

ReactJS Refs

ReactJS Refs

The example below shows how to use refs for clearing input area. The ClearInput function searches for item with the value ref = "myInput," resets the state, and adds the focus after clicking on 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}>Click here to Clear text</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'));

The above code will display the following output-

Output

reactjs Refs


No Sidebar ads