Reputation: 788
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.
Need to create 3 useRef
s to point to 3 buttons.
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'));```
Upvotes: 34
Views: 25596
Reputation: 4540
ref
s 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>
);
});
}
Upvotes: 100