36

I want to have refs in functional components which have elements dynamically rendered.

Please help me in creating Dynamic Refs using the useRef Hook and accessing it in the handler.

  1. Need to create 3 useRefs to point to 3 buttons.

  2. Access them in the button handler using "ref1.value" Or "ref2.value" etc.

let abc=[1,2,3];
function submitclick(){
    alert(123);
}

// Here I want to access the buttons using the refs
return ( <div>
  {  abc.map(function(index){ return (<button ref='123' onClick={submitclick}>{`Button${index}`}</button>)})}
    </div>);
};

ReactDOM.render(<MyComponent name="doug" />, document.getElementById('root'));```
2
  • What did you try? Do you read the docs? Commented Sep 5, 2019 at 17:31
  • 1
    why do you need useRef here in the first place? Commented Sep 5, 2019 at 17:33

1 Answer 1

102

refs are basically objects, and they have a default key current. So, you can create an array of refs like this:

const myRefs= useRef([]);

Then you can populate this array of refs like this:

ref={el => (myRefs.current[i] = el)}

Here is the full version:

{
  [1, 2, 3].map((v, i) => {
    return (
      <button
        ref={(el) => (myRefs.current[i] = el)}
        id={i}
        onClick={submitClick}
      >{`Button${i}`}</button>
    );
  });
}
Sign up to request clarification or add additional context in comments.

3 Comments

for anyone wondering about the Typescript usage, simply add a ! - ref={(el) => (myRefs.current[i] = el!)}
This works, but could someone please briefly describe what's going on here when passing such a function as ref prop (or add a link to the docs)? Thanks!
@PhilJay Check out callback refs, and more here: react.dev/reference/react-dom/components/common#ref-callback

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.