ReactJS – createRef() method

ReactJSWeb DevelopmentFront End Technology

In this article, we are going to see how to create a reference to any DOM element in the functional component.

This method is used to access any DOM element in a component and it returns a mutable ref object which will be persisted as long as the component is placed in the DOM. If we pass a ref object to any DOM element, then the. current property to the corresponding DOM node elements will be added whenever the node changes.

Syntax

React.createRef()

Example

In this example, we will build a React application that will pass the ref object to two input fields and when clicked on the button, it will automatically fetch the data of these input fields.

App.jsx

import React from 'react';

class App extends React.Component {
   constructor(props) {
      super(props);
      this.fetchUsername = this.fetchUsername.bind(this);
      this.fetchEmail = this.fetchEmail.bind(this);
   }
   fetchUsername() {
      this.refs.username.value = 'RahulBansal123';
   }
   fetchEmail() {
      this.refs.email.value = 'rahul@gmail.com';
   }
   render() {
      return (
         <div>
            <input type="text" ref="username" />
            <input type="text" ref="email" />
            <button type="button" onClick={this.fetchUsername}>
               Username
            </button>
            <button type="button" onClick={this.fetchEmail}>
               Email
            </button>
         </div>
      );
   }
}
export default App;

In the above example, when the Username or Email button is clicked, then the fetchUsername and fetchEmail function is called respectively which pass the ref object to the input fields and change its value from null to some text.

Output

This will produce the following result.

raja
Published on 18-Mar-2021 11:49:21
Advertisements