Skip to main content

Featured Post

What’s new in C# 14.0

  Features of C# 14.0  🧩 1️⃣ Field-backed Properties (0:40 – 1:00) Pehla feature hai — Field-backed Properties Ab aapko manually private field likhne ki zarurat nahi. C# 14 mein ek naya contextual keyword aaya hai — field public string Name { get ; set => field = value ?? throw new ArgumentNullException( nameof ( value )); } Yahaan field compiler-generated backing field ko represent karta hai. Validation ya logic likhna ab super easy ho gaya hai! 🧩 2️⃣ Extension Members (1:00 – 1:25) Dusra feature — Extension Members Pehle hum sirf extension methods bana sakte the, ab hum properties , events , aur static members bhi extend kar sakte hain! public static class StringExtensions { public static int WordCount ( this string str) => str.Split( ' ' ).Length; } Ab koi bhi string par .WordCount() laga ke result le sakte ho — reusability aur readability dono badh gayi! 💪 🧩 3️⃣ Null-Conditional Assignment (1:25 – 1:50) ...

What is Refs in React


Refs is the shorthand used for references in React. It is similar to keys in React. It is an attribute which makes it possible to store a reference to particular DOM nodes or React elements. It provides a way to access React DOM nodes or React elements and how to interact with it. It is used when we want to change the value of a child component, without making the use of props.

When to Use Refs

Refs can be used in the following cases:

When we need DOM measurements such as managing focus, text selection, or media playback.

It is used in triggering imperative animations.

When integrating with third-party DOM libraries.

It can also use as in callbacks.

When to not use Refs

Its use should be avoided for anything that can be done declaratively. For example, instead of using open() and close() methods on a Dialog component, you need to pass an isOpen prop to it.

You should have to avoid overuse of the Refs.

How to create Refs

In React, Refs can be created by using React.createRef(). It can be assigned to React elements via the ref attribute. It is commonly assigned to an instance property when a component is created, and then can be referenced throughout the component.

class MyComponent extends React.Component {  

  constructor(props) {  

    super(props);  

    this.callRef = React.createRef();  

  }  

  render() {  

    return <div ref={this.callRef} />;  

  }  

}  

How to access Refs

In React, when a ref is passed to an element inside render method, a reference to the node can be accessed via the current attribute of the ref.

const node = this.callRef.current;  

Refs current Properties

The ref value differs depending on the type of the node:

When the ref attribute is used in HTML element, the ref created with React.createRef() receives the underlying DOM element as its current property.

If the ref attribute is used on a custom class component, then ref object receives the mounted instance of the component as its current property.

The ref attribute cannot be used on function components because they don't have instances.

Add Ref to DOM elements

In the below example, we are adding a ref to store the reference to a DOM node or element.

import React, { Component } from 'react';  

import { render } from 'react-dom';  

   class App extends React.Component {  

  constructor(props) {  

    super(props);  

    this.callRef = React.createRef();  

    this.addingRefInput = this.addingRefInput.bind(this);  

  }

     addingRefInput() {  

    this.callRef.current.focus();  

  }  

     render() {  

    return (  

      <div>  

        <h2>Adding Ref to DOM element</h2>  

        <input  

          type="text"  

          ref={this.callRef} />  

        <input  

          type="button"  

          value="Add text input"  

          onClick={this.addingRefInput}  

        />  

      </div>  

    );  

  }  

}  

export default App;  

Output

React Refs

Add Ref to Class components

In the below example, we are adding a ref to store the reference to a class component.

Example

import React, { Component } from 'react';  

import { render } from 'react-dom';  

function CustomInput(props) {  

  let callRefInput = React.createRef();     

  function handleClick() {  

    callRefInput.current.focus();  

  }     

  return (  

    <div>  

      <h2>Adding Ref to Class Component</h2>  

      <input  

        type="text"  

        ref={callRefInput} />  

      <input  

        type="button"  

        value="Focus input"  

        onClick={handleClick}  

      />  

    </div>  

  );  

}  

class App extends React.Component {  

  constructor(props) {  

    super(props);  

    this.callRefInput = React.createRef();  

  }    

  focusRefInput() {  

    this.callRefInput.current.focus();  

  }     

  render() {  

    return (  

      <CustomInput ref={this.callRefInput} />  

    );  

  }  

}  

export default App;  

Output

React Refs

Callback refs

In react, there is another way to use refs that is called "callback refs" and it gives more control when the refs are set and unset. Instead of creating refs by createRef() method, React allows a way to create refs by passing a callback function to the ref attribute of a component. It looks like the below code.

<input type="text" ref={element => this.callRefInput = element} />  

The callback function is used to store a reference to the DOM node in an instance property and can be accessed elsewhere. It can be accessed as below:

this.callRefInput.value  

The example below helps to understand the working of callback refs.

import React, { Component } from 'react';  

import { render } from 'react-dom';   

class App extends React.Component {  

    constructor(props) {  

    super(props);    

    this.callRefInput = null;    

    this.setInputRef = element => {  

      this.callRefInput = element;  

    };    

    this.focusRefInput = () => {  

      //Focus the input using the raw DOM API  

      if (this.callRefInput) this.callRefInput.focus();  

    };  

  }   

  componentDidMount() {  

    //autofocus of the input on mount  

    this.focusRefInput();  

  }    

  render() {  

    return (  

      <div>  

    <h2>Callback Refs Example</h2>  

        <input  

          type="text"  

          ref={this.setInputRef}  

        />  

        <input  

          type="button"  

          value="Focus input text"  

          onClick={this.focusRefInput}  

        />  

      </div>  

    );  

  }  

}  

export default App;  

In the above example, React will call the "ref" callback to store the reference to the input DOM element when the component mounts, and when the component unmounts, call it with null. Refs are always up-to-date before the componentDidMount or componentDidUpdate fires. The callback refs pass between components is the same as you can work with object refs, which is created with React.createRef().

Output

React Refs

Forwarding Ref from one component to another component

Ref forwarding is a technique that is used for passing a ref through a component to one of its child components. It can be performed by making use of the React.forwardRef() method. This technique is particularly useful with higher-order components and specially used in reusable component libraries. The most common example is given below.

Example

import React, { Component } from 'react';  

import { render } from 'react-dom';  

const TextInput = React.forwardRef((props, ref) => (  

  <input type="text" placeholder="Hello World" ref={ref} />  

));    

const inputRef = React.createRef();  

class CustomTextInput extends React.Component {  

  handleSubmit = e => {  

    e.preventDefault();  

    console.log(inputRef.current.value);  

  };  

  render() {  

    return (  

      <div>  

        <form onSubmit={e => this.handleSubmit(e)}>  

          <TextInput ref={inputRef} />  

          <button>Submit</button>  

        </form>  

      </div>  

    );  

  }  

}  

export default App;  

In the above example, there is a component TextInput that has a child as an input field. Now, to pass or forward the ref down to the input, first, create a ref and then pass your ref down to <TextInput ref={inputRef}>. After that, React forwards the ref to the forwardRef function as a second argument. Next, we forward this ref argument down to <input ref={ref}>. Now, the value of the DOM node can be accessed at inputRef.current.

React with useRef()

It is introduced in React 16.7 and above version. It helps to get access the DOM node or element, and then we can interact with that DOM node or element such as focussing the input element or accessing the input element value. It returns the ref object whose .current property initialized to the passed argument. The returned object persist for the lifetime of the component.

Syntax

const refContainer = useRef(initialValue);  

Example

In the below code, useRef is a function that gets assigned to a variable, inputRef, and then attached to an attribute called ref inside the HTML element in which you want to reference.

function useRefExample() {  

  const inputRef= useRef(null);  

  const onButtonClick = () => {  

    inputRef.current.focus();  

  };  

  return (  

    <>  

      <input ref={inputRef} type="text" />  

      <button onClick={onButtonClick}>Submit</button>  

    </>  

  );  

}  

Comments

Popular posts from this blog

Conditional Statement in Python

It is used to solve condition-based problems using if and else block-level statement. it provides a separate block for  if statement, else statement, and elif statement . elif statement is similar to elseif statement of C, C++ and Java languages. Type of Conditional Statement:- 1) Simple if:- We can write a single if statement also in python, it will execute when the condition is true. for example, One real-world problem is here?? we want to display the salary of employees when the salary will be above 10000 otherwise not displayed. Syntax:- if(condition):    statements The solution to the above problem sal = int(input("Enter salary")) if sal>10000:     print("Salary is "+str(sal)) Q)  WAP to increase the salary of employees from 500 if entered salary will be less than 10000 otherwise the same salaries will be displayed. Solution:- x = int(input("enter salary")) if x<10000:     x=x+500 print(x)   Q) WAP to display th...

DSA in C# | Data Structure and Algorithm using C#

  DSA in C# |  Data Structure and Algorithm using C#: Lecture 1: Introduction to Data Structures and Algorithms (1 Hour) 1.1 What are Data Structures? Data Structures are ways to store and organize data so it can be used efficiently. Think of data structures as containers that hold data in a specific format. Types of Data Structures: Primitive Data Structures : These are basic structures built into the language. Example: int , float , char , bool in C#. Example : csharp int age = 25;  // 'age' stores an integer value. bool isStudent = true;  // 'isStudent' stores a boolean value. Non-Primitive Data Structures : These are more complex and are built using primitive types. They are divided into: Linear : Arrays, Lists, Queues, Stacks (data is arranged in a sequence). Non-Linear : Trees, Graphs (data is connected in more complex ways). Example : // Array is a simple linear data structure int[] number...

Top 50 Most Asked MERN Stack Interview Questions and Answers for 2025

 Top 50 Most Asked MERN Stack Interview Questions and Answers for 2025 Now a days most of the IT Company asked NODE JS Question mostly in interview. I am creating this article to provide help to all MERN Stack developer , who is in doubt that which type of question can be asked in MERN Stack  then they can learn from this article. I am Shiva Gautam,  I have 15 Years of experience in Multiple IT Technology, I am Founder of Shiva Concept Solution Best Programming Institute with 100% Job placement guarantee. for more information visit  Shiva Concept Solution 1. What is the MERN Stack? Answer : MERN Stack is a full-stack JavaScript framework using MongoDB (database), Express.js (backend framework), React (frontend library), and Node.js (server runtime). It’s popular for building fast, scalable web apps with one language—JavaScript. 2. What is MongoDB, and why use it in MERN? Answer : MongoDB is a NoSQL database that stores data in flexible, JSON-like documents. It...