How to create dynamic refs in functional component- Using useRef Hook

refs are basiclly 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>
    );
  });
}

Leave a Comment