Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React How to set an element's ref value using a variable

Tags:

reactjs

So I have something very simple:

<TextField ref={id}/>

I am wondering how I would use a variable as a ref, instead of a string? I kind of need this because this element is being generated in the render method, just before the return method. So I am using refs that are just created in a for loop.

like image 556
pizzae Avatar asked Jan 04 '23 16:01

pizzae


2 Answers

<TextField ref={(ref) => this.myRefName = ref} />

Then you can access it via this.myRefName ie console.log(this.myRefName)

like image 169
alpha Avatar answered Jan 08 '23 05:01

alpha


You can make use of ref callback to access ref via a variable rather than a string

<TextField ref={(input) => this.myField = input}/>

Now you can refer to TextField like this.myField

Ref callback doc

like image 37
Shubham Khatri Avatar answered Jan 08 '23 06:01

Shubham Khatri