crowhill
crowhill

Reputation: 2558

Dynamically creating refs without strings

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!

Upvotes: 1

Views: 106

Answers (4)

Thaman Chand
Thaman Chand

Reputation: 36

[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;

Upvotes: 0

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85593

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.

Upvotes: 0

ageoff
ageoff

Reputation: 2828

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>
  ))
)

Upvotes: 1

nbwoodward
nbwoodward

Reputation: 3166

Try just:

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

Upvotes: 1

Related Questions