August 6, 2020

How to get a DOM element in react?

In react, there may be a case you need to perform some operation on dom elements or you will be using some third party library that wants dom element as input.

Then we can achieve accessing DOM using two below recommend method

  • createRef
  • useRef

CreateRef

createRef() method creates a mutable object, and we can its reference to the DOM element like below

import React, { useState, useRef, Component } from 'react';
import logo from './logo.svg';
import './App.css';
export default class App extends Component {
  state = {
    counter: 0
  }
  constructor() {
    super()
    this.ref = React.createRef();
  }
  render() {
    return (<div className="App" ref={this.ref}>
      {this.state.counter}
      <button onClick={() => this.setState({
        counter: this.state.counter + 1
      })}>Increament</button>
    </div>)
  }

}

As you can see this.ref to the div component, so we can access dom reference using this.ref.current, current property contains the dome element

As createRef() returns mutable object then it doesn’t affect rendered cycle.

We can’t use createRef in functional components

for eg.

import React,{useState, createRef} from 'react';
import logo from './logo.svg';
import './App.css';

function App() {
   const [counter, setCounter] = useState(0)
  const ref = React.createRef();
 

  return (
    <div className="App" ref={ref}>
      {counter}
      <button onClick={()=>setCounter(counter+1)}>Increament</button>
    </div>
  );
}

export default App;

As you can see in the above example we have an increment button, which changes counter state and force above functional component to re-render, which means variable ref again get initialized with an initial null value, so that’ why createRef is not useful in the functional component.

So, In such kind of cases useRef comes for rescue

useRef

useRef() method also returns the mutable object, which means it doesn’t affect the rendering of the functional component.

for eg.

import React,{useState, useRef} from 'react';
import logo from './logo.svg';
import './App.css';

function App() {
   const [counter, setCounter] = useState(0)
  const ref = useRef(null);
 

  return (
    <div className="App" ref={ref}>
      {counter}
      <button onClick={()=>setCounter(counter+1)}>Increament</button>
    </div>
  );
}

export default App;

As you can see above we have assigned a ref object to a div element, reference of the div element will be in ref.current property.

The only difference between useRef and createRef is that useRef remembers the value of the dom even though component rerenders

Leave a Reply

Your email address will not be published. Required fields are marked *