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.
[ ]
brackets for dynamic variable names instead of dot – Ozgur Sar Dec 3 '20 at 8:28this[`${el + index}`]
? I tried this too but unable to get the value ofthis.el5
– Neel Dsouza Dec 3 '20 at 8:39this
. How/when/where isdisplayXmasTreeParts
called? Please provide a more complete example. – Felix Kling Dec 3 '20 at 9:12