Blog React How to use Ref in React
Blog React How to use Ref in React

Refs are nothing but a way to access React elements or Dom nodes created in the Render method of React. Refs can be used in class components as well as in functional components. The normal flow of a interact to child components by parents are props.

But the issue with props is that they re render the child components again once they are changed. There will be a case where you want to modify Dom nodes or React elements without using the props in that case you will gonna use Refs.

Where to use Refs in React

Some of the good places you can use refs are:-

  • When integrating with 3rd party Dom libraries.
  • Getting, setting and focusing inputs.
  • Adding and removing animations on elements.

When not to use Refs in React

  • You should not use refs if same task can be done using declaratively.
  • If same thing can be done using state by keeping best performance.

How to create Refs in class Components

Refs can be created in class components using the syntax React.createRef(). Most of the time refs are created in the constructor. The last step is to attach ref to the node. Let’s take a look at below example:-

class RefExample extends React.Component {
  constructor(props) {
    super(props);
    this.refExample = React.createRef(); //ref created
  }
  render() {
    return <div ref={this.refExample} />; // ref attached
  }
}

In the above example we created the ref in constructor and assign it to this. So, that we can access it in render. And to attach ref to a node we just need to pass it ref prop.

How to create Ref in Functional components

There is a old way of using ref in functional component using forwardRef. But we gonna use new hook way to use ref in functional component using useRef.

import React, { useRef } from "react";

function App() {

  const refExample = useRef(null); // create ref

  return (
    <div>
      <input ref={refExample}/> // attach ref
    </div>
  );
}

How to access ref in React

We can access ref using the syntax this.refExample.current; and syntax is equivalent to the document.getElementById(‘unique-id’);.

Examples:-

  • To access whole node this.refExample.current;.
  • Focus element this.refExample.current.focus();.
  • Get value of input this.refExample.current.value;.
  • Set value of input this.refExample.current.value = newValue;.
  • To play video this.refExample.current.play();.
  • To pause video this.refExample.current.pause();.

ref

If you want to learn React.memo you can check here.

Categories: Reactjs

3 Comments

Forwarding refs to Child components in Reactjs - Blog React · January 28, 2020 at 4:14 am

[…] If you want to learn how to use ref you can check here. […]

What's new in React v16.13.0 - Blog React · February 29, 2020 at 4:28 am

[…] Learn to use Refs in React in this article. […]

Comments are closed.