StillDead
StillDead

Reputation: 2079

How to get dynamic ref on React

I have an element with this ref

ref={`inner-player${this.props.position}`}

and in a function I need to work with that ref doing something like this

const chipBetImage = this.refs.inner-player${this.props.position};

but I am getting an error

./app/components/ui/PlayerSlot/index.js
Module build failed: SyntaxError: /home/marcelo/Documents/Projects/application-playerinterface/app/components/ui/PlayerSlot/index.js: Unexpected token (150:50)
  148 |       this.props.addMoney({position : this.props.position, currentBet : this.props.currentBet});
  149 |     } else {
> 150 |       const chipBetImage = this.refs.inner-player${this.props.position};
      |                                                   ^
  151 |       chipBetImage.classList.add('animated', 'pulse');

so, which is the way to do this ?

Upvotes: 1

Views: 1668

Answers (1)

Felix Kling
Felix Kling

Reputation: 817030

${} is only valid inside template literals. this.refs.inner-player${this.props.position}; is not a template literal.

If you want to use a computed property name, you have to use bracket notation:

this.refs[`inner-player${this.props.position}`]

See Dynamically access object property using variable .

Upvotes: 2

Related Questions