How to create multiple refs in React with useRef

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";

2. Declare your Refs. The default value should be an array.

let usernameRefs = useRef([]);

3. 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()
)

4. Create a function to handle copying the input field.

const handleCopyUsername = (e, index) => {
usernameRefs.current[index].current.select();
document.execCommand("copy");
};

5. 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>)})

6. 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)

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store