Search code examples
reactjsref

Is it possible to have a dynamic ref in react js?


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()}
            </>
        );
    }
}

Solution

  • 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!