This can be achieved simply, your approach is correct just some few fixes.
- You can return only one element in JSX
- The ref should be maintained somewhere in JS memory
Check this code and the working codesandbox instance here
class Test extends React.Component {
constructor() {
super();
this.inputRef = React.createRef();
}
hide = () => {
console.log(this.inputRef);
this.inputRef.current.style.visibility="hidden";
};
render() {
return (
<>
<span ref={this.inputRef} id="test-id" className="">
The Quick Brown Fox.
</span>
<button onClick={() => this.hide()}>Hide</button>
</>
);
}
}
EDIT! As you asked about dynamically generated refs...
This is what I understood as your requirement... see whether it matches it.
Working sandbox here
class Test extends React.Component {
constructor() {
super();
this.inputRef = React.createRef();
this.refCollection = {};
for (let id = 0; id < 10; id++) {
this.refCollection["id_" + id] = React.createRef();
}
}
hide = e => {
console.log(this.inputRef);
this.inputRef.current.style.visibility = "hidden";
};
hideInCollection = k => {
let changedRef = this.refCollection[k];
changedRef.current.style.visibility = "hidden";
};
render() {
return (
<>
<span ref={this.inputRef} id="test-id" className="">
The Quick Brown Fox.
</span>
<button onClick={() => this.hide()}>Hide</button>
{Object.keys(this.refCollection).map(k => (
<div>
<span ref={this.refCollection[k]} id="test-id" className="">
Looped the Quick Brown Fox
</span>
<button onClick={() => this.hideInCollection(k)}>Hide</button>
</div>
))}
</>
);
}
}