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.




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.


import React from 'react';

class App extends React.Component {
   constructor(props) {
      this.fetchUsername = this.fetchUsername.bind(this);
      this.fetchEmail = this.fetchEmail.bind(this);
   fetchUsername() {
      this.refs.username.value = 'RahulBansal123';
   fetchEmail() { = '';
   render() {
      return (
            <input type="text" ref="username" />
            <input type="text" ref="email" />
            <button type="button" onClick={this.fetchUsername}>
            <button type="button" onClick={this.fetchEmail}>
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.


This will produce the following result.

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