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

--

--

--

Growth at Moni(YC W22) | Adebola.dev

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

BootstrapVue — Toasts, Alerts, and Tooltips

How to create DYNAMIC ROUTING and fetch data DYNAMICALLY in REACT JS

This Week in L2Code: Execution Stack

Publish Github Package

How to Automatically Reload a Page After a Given Period of Inactivity in JavaScript?

Flux: Some things never change

Intro to Angular Directives

How to Check for text-overflow Ellipsis in an HTML Element?

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
Adebola Adeniran

Adebola Adeniran

Growth at Moni(YC W22) | Adebola.dev

More from Medium

How to submit a form on Netlify with React Final Form.

How to use React and Tone.js to make a simple web audio application

Modular Synth

Website Clone, Using React.

React HOC