Adebola's Blog

How to create multiple refs in React with useRef

July 27, 2020

In this article, you’ll also learn how to copy text inside multiple input fields in React using useRef.

I needed to create multiple readonly input fields in a React component that a user can then click a button to select copy the text inside that input field. It took me a couple of hours to figure it out.

After reading several stackoverflow articles, here’s exactly how you do it.

  1. First, import useRef()
import React, { useRef, useState, useEffect } from "react"
  1. Declare your Refs. The default value should be an array.
let usernameRefs = useRef([])
  1. Dynamically create as many refs as you want. Assume we will have 4 input elements on the page — so we use an array with a length of 4.
usernameRefs.current = [0, 0, 0, 0].map(
  (ref, index) => (usernameRefs.current[index] = React.createref())
)
  1. Create a function to handle copying the input field.
const handleCopyUsername = (e, index) => {
  usernameRefs.current[index].current.select()
  document.execCommand("copy")
}
  1. Finally, create the 4 input elements.
;[0, 0, 0, 0].map((el, index) => {
  return (
    <div>
      <input
        type="text"
        readonly
        ref={usernameRefs.current[index]}
        value={index}
      />
      )<button onClick={handleCopyUsername}>Click to copy text </button>{" "}
    </div>
  )
})
  1. And that’s it. When you click your click to copy text button, you should get have the input value(in our case just the index, copied to the clipboard)

Here’s a link to the Github gist for the full code. Gist


Written by Adebola Adeniran, I love Nigerian Jollof (> Ghana jollof) and Plantain. Follow me on Twitter.