0

I am trying to find a way to use generic variable and function calling. Like setting a reference in react dynamically, depending on another variable.

An vision of what I would like to get is:

ref={ref => (eval(`this.${this.props.controlId}`) = ref)}

which would end up being something like

this.props.controlId = "myid"

ref={ref => (this.myid = ref)}
Daniel
  • 37
  • 5

1 Answers1

0

Well, you can destruct the props like:

const { controlId : myId } = this.props; // renamed to myId
ref={ref => (this[myId] = ref)} // <---here you can use it.

In your case you can use [] notation for this:

ref={ref => (this[this.props.controlId]= ref)}
Jai
  • 74,255
  • 12
  • 74
  • 103