1

I want to create multiple refs for 40 divs without using React.createRef(). But I'm unable to create dynamic variable name for my ref. I'm using below code to create ref.

const displayXmasTreeParts = () => Array(40).fill().map((el, index) => (
  <div className={`xmasTreePart${randomClass}`} key={`part${index}`} 
     ref={el => [this.el`${index}`] = el}/>
);

const handleClick = () => this.el5.classList.add(`new-class`);

render() {
  return (
    <div className="xmasTree">
      {this.displayXmasTreeParts()}
    </div>
    <button className="SetUpTree" onClick={this.handleClick}>Click here to reveal Our Xmas Tree</button>
)}

I also tried this ref={el => `this.el${index}` = el}

But getting this error Invalid left-hand side in assignment expression in both cases.

5
  • You need to use [ ] brackets for dynamic variable names instead of dot Commented Dec 3, 2020 at 8:28
  • Do u mean this[`${el + index}`] ? I tried this too but unable to get the value of this.el5 Commented Dec 3, 2020 at 8:39
  • Are you using a functional component? They don't really have an instance you can refer to, certainly not via this. How/when/where is displayXmasTreeParts called? Please provide a more complete example. Commented Dec 3, 2020 at 9:12
  • why don't you store the refs in array ?! Commented Dec 3, 2020 at 12:55
  • I'm using Class Component. displayXmasTreeParts() is called from render() function. Commented Dec 3, 2020 at 12:55

2 Answers 2

2

How about

ref={el => {this["el"+index] = el}}/>
Sign up to request clarification or add additional context in comments.

1 Comment

This works perfectly fine to create dynamic variable. Thanks
1

you need to store the refs in array

class Component {
    
    let _refs = [];
    
    displayXmasTreeParts = () => Array(40).fill().map((el, index) => {
    
        _refs = [];
    
        return (
           <div className={`xmasTreePart${randomClass}`} key={`part${index}`} 
                ref={el => _refs.push(el)}/>
           );
    }
    
    
    ...

    
}

2 Comments

But is there a way we can have dynamic variable name which has this keyword?
I don't know about dynamic variables, but I think having an array is a better data structure for your case

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.