4

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.

2 Answers 2

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

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

Sign up to request clarification or add additional context in comments.

3 Comments

How do you assign the "myRefName" to become a variable? If I try to use "this.i" (i is from the for loop), and I log out "this", I can only see 1 reference to i. How would I dynamically create different refnames?, i.e. ref1, ref2, ref3, without typing it out?
You can make use of bracket notation and es6 template string, example: <TextField ref={(ref) => this[`ref${i}`] = ref} />
Just what I needed
1

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

1 Comment

How do you assign the "myRefName" to become a variable? If I try to use "this.i" (i is from the for loop), and I log out "this", I can only see 1 reference to i. How would I dynamically create different refnames?, i.e. ref1, ref2, ref3, without typing it out?

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.