Reputation: 1067
Is it possible to have a dynamic ref in react js.
I want to assign a dynamic value in ref of span.
I dont have any idea how to call the dynamic ref.
class Test extends React.Component {
constructor() {
super();
}
hide = () =>{
const span = this.refs.ref-1; // I dont have any idea how to call the dynamic ref here.
span.className = "hidden";
}
table = () =>{
//postD is something axios request;
const tableDetail = Object.keys(postD).map((i) => (
<div key={i}>
<h2>{ postD[i].title }</h2>
<p>{ postD[i].content }</p>
<span ref={"ref-"+postD[i].id} id="test">The Quick Brown Fox.</span> --> the ref is like ref="ref-1" and ref="ref-2" and ref="ref-3" so on.. it is dynamic
<button onClick={() => this.hide()} >Like</button>
</div>
}
render() {
return (
<>
<h2>Table</h2>
{this.table()}
</>
);
}
}
Upvotes: 1
Views: 565
Reputation:
By updating below two methods you will get the solutions.
Pass id
in hide
method.
table = () => {
const tableDetail = Object.keys(postD).map((i) => (
<div key={i}>
<h2>{postD[i].title}</h2>
<p>{postD[i].content}</p>
<span ref={`ref-${postD[i].id}`} id={`test-${postD[i].id}`}>The Quick Brown Fox.</span>
<button onClick={() => this.hide(postD[i].id)} >Like</button>
</div>
));
}
Use same id
to get the ref.
hide = (id) => {
const span = ReactDOM.findDOMNode(this.refs[`ref-${id}`]);
span.className = "hidden";
}
Hope this will help!
Upvotes: 3
Reputation: 71
You can use below snippet. I have updated your class. Just pass "id" to the hide method.
class Test extends React.Component {
constructor() {
super();
}
hide = (id) => {
const span = this.refs[`ref-${id}`];
span.ClassName = "hidden";
}
table = () => {
const tableDetail = Object.keys(postD).map((i) => (
<div key={postD[i].id}>
<h2>{postD[i].title }</h2>
<p>{postD[i].content }</p>
<span ref={`ref-${postD[i].id}`} id={`${postD[i].id}`}>The Quick Brown Fox.</span>
<button onClick={() => this.hide(postD[i].id)} >Like</button>
</div>
}
render() {
return (
<>
<h2>Table</h2>
{this.table()}
</>
);
}
}
Upvotes: 0