1

EDIT: We're using React 16.2.0, which is relevant to the question (see this answer).

So far as I can tell, this is the accepted way to create a ref (at least for our version of react):

<div ref={(r) => { this.theRef = r; }}>Hello!</div>

And then it can be used something like this:

componentDidMount() {
  if (this.theRef) {
    window.addEventListener('scroll', this.handleScroll);
  }
}

This works fine. However, if I want to create a dynamically named ref, say as part of a loop, how do I go about naming the ref?

Put in now obsolete terms, I would like something along these lines:

<div ref="{refName}">Hello!</div>

Thanks!

crowhill
  • 2,398
  • 3
  • 26
  • 55

4 Answers4

1

Try just:

<div ref={refName}>Hello!</div>
nbwoodward
  • 2,816
  • 1
  • 16
  • 24
  • "using string literals in ref attributes is depreciated." [see here](https://stackoverflow.com/questions/43873511/deprecation-warning-using-this-refs) – crowhill Aug 29 '18 at 19:27
1

For a map you need a key, so maybe you could just use that key to map to an object? Like so:

this.myRefs = {}

doSomethingToRef = (key) => {
  this.myRefs[key].doSomething()
}

return (
  myValues.map(value => (
    <div key={value.key} ref = {r => {this.myRefs[value.key] = r}}>{...}</div>
  ))
)
ageoff
  • 2,798
  • 2
  • 24
  • 39
0

Use ref like this:

Define the refName inside the class constructor:

this.refName = React.createRef()

Assign the ref in your element:

<div ref={this.refName} id="ref-name">Hello!</div>

To access the refName, use current:

this.refName.current

Example:

if (this.refName.current.id == 'ref-name') {
  window.addEventListener('scroll', this.handleScroll);
}

Update

As per your comment, to use ref in older version, you may use just like this:

<div ref={(el) => this.refName = el} id="ref-name">Hello!</div>
{/* notice double quote is not used */}

To access:

this.refs.refName

Example:

if (this.refs.refName.id == 'ref-name') {
  window.addEventListener('scroll', this.handleScroll);
}

To do it in more better way, you may use callback pattern.

Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231
0

[short-id][1] might be a good candidate!

It has methods like:

ids.store('foo');  // "8dbd46"
ids.fetch('8dbd46');  // 'foo'
ids.fetch('8dbd46');  // undefined
ids.configure(Object conf)



$ npm install short-id

RefsCmp.js

var shortid = require('shortid');

const RefsList = (newrefs) = > (
   {newrefs.map(item => (
      <div ref={shortid.generate()}>Hello!</div>
   ))}
)

export default RefsList;