Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

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

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

2) Access them in 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 with 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'));```
like image 385
Sumanth madey Avatar asked Sep 05 '19 17:09

Sumanth madey


People also ask

Can I use useRef in functional component?

The useRef is a hook that allows to directly create a reference to the DOM element in the functional component. Syntax: const refContainer = useRef(initialValue); The useRef returns a mutable ref object.

How do you add a ref to a functional component?

To create a ref in a functional component we use the useRef() hook which returns a mutable object with a . current property set to the initialValue we passed to the hook. This returned object will persist for the full lifetime of the component. Thus, throughout all of its re-rendering and until it unmounts.

Can we use refs in functional component?

When the ref attribute is used on a custom class component, the ref object receives the mounted instance of the component as its current . You may not use the ref attribute on function components because they don't have instances.


1 Answers

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>
    );
  });
}
like image 197
user9408899 Avatar answered Oct 17 '22 09:10

user9408899