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.


import React from 'react';
import ReactDOM from 'react-dom';

class App extends React.Component {
   constructor(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: ''});
   render() {
      return (
            <input value = {this.state.data} onChange = {this.updateState} 
               ref = "myInput"></input>
            <button onClick = {this.clearInput}>Click here to Clear text</button>
export default App;


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-


reactjs Refs