How to create multiple refs in React with useRef

How to copy text from multiple input fields using 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()

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

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.

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

5. Finally, create the 4 input elements.

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)



Growth at Moni(YC W22) |

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