useRef in React

Hi, in this post we are going to see how to use the “useRef” hook in an example.

useRef is the way that React use the get an element from the DOM this is similar to the selectors document.getElementById() or document.getElementsByClassName(), etc.

Let’s get/select this div from the DOM:

1.– So the first thing that we need to do is import the “useRef” hook from React

import React, {useRef, useState} from 'react'

2.- Then inside our component create an instance of useRef() method.

 function App() {
    // Ref
    const divElement = useRef(null)

3.- Insert ref={ } in the element that you want to get with the created instance like this:

  return (
    <div ref={divElement}>
...

4.- Finally if we console the divElement then we are going to see the selected div:

function App() {
  // Ref
  const divElement = useRef()
  console.log('divElement ===>', divElement)
...

Result:

Nice! now we need to specify the current (is the div that we want to get):

function App() {
  // Ref
  const divElement = useRef(null)
  console.log('divElement ===>', divElement.current)

Result:

Nice, that’s the way to get elements.

Also if you want to get the form element you can do:

divElement.current.children[0]

Result:

Here the entire code:

// Dependencies
import React, {useRef, useState} from 'react'

// Child component
function Name({name, onNameChange}) {
  return (
    <div>
      <label htmlFor="name">Name: </label>
      <input id="name" value={name} onChange={onNameChange} />
    </div>
  )
}

function App() {
  // Ref
  const divElement = useRef(null)
  console.log('divElement ===>', divElement.current.children[0])

  // Local state
  const [name, setName] = useState('')

  return (
    <div ref={divElement}>
      <form>
        <Name name={name} onNameChange={event => setName(event.target.value)} />
      </form>
    </div>
  )
}

By Cristina Rojas.