Refs and the DOM

Refs :- Refs is the short hand for References in React. It is an attribute which helps to store a reference to a particular DOM nodes or React elements. Refs can be useful when we need DOM measurements or to add methods to the components. we will discuss refs and the DOM in next paragraph.

Refs and the DOM

Using Refs:

Following are the cases when refs should be used:

  • Managing focus, text selection, or media playback.
  • Triggering imperative animations.
  • Integrating with third-party DOM libraries.

How to create Refs in React >=16.3 ?

We are creating Refs using React.createRef() and React elements attached with refs attribute. Refs commonly assignee to an instance feature.

Note :- Strictly, you don’t use the ref attribute on functional components because functional components don’t have instances.

Access Refs using this.myInput.current;

How to add Ref to DOM Element ?

In below code adding refs to DOM node or element.

React assign the current property with the DOM element when the component mounts, and assign it back to null when it unmounts. ref updates before componentDidMount or componentDidUpdate lifecycle of component.

How to add Ref to class component ?

In below code adding refs to class component.

When you need refs instead of ID’s ?

Everybody know about, ID’s works only a single element in whole DOM tree. In-case of you are using multiple elements with same ID’s. Then we use refs and we can replace the IDs with the a particular ref name and It will be work fine. Refs work for these scenario’s.

  • Managing focus, text selection, or media playback.
  • Integrating with third-party DOM libraries.
  • Triggering imperative animations.
Categories: React

Leave a Reply

Be the First to Comment!

avatar
  Subscribe  
Notify of
Please wait...

Subscribe to our newsletter

Want to be notified when our article is published? Enter your email address and name below to be the first to know.