а

Using ref in React


#1

Hi,

Based on the blog post, I see that it is using

// componentDidMount()
gantt.init(this.ganttContainer);

// Render
<div
        ref={(input) => { this.ganttContainer = input }}
        style={{ width: '100%', height: '100%' }}
></div>

I am currently using just the div id to pass into gantt.init.

// componentDidMount()
gantt.init(gantt);

// Render
<div id='gantt'
        style={{ width: '100%', height: '100%' }}
></div>

I am wondering if there is a difference if I am not use ref to get the ganttContainer (DOM?) reference.
Any benefit or reason for using ref?

Thanks!


#2

Hello Joseph,
I don’t specialize in React so I won’t be able to explain how React components work. But I suspect that it might be used in complex projects and it might provide a more flexible way to control the elements. You can read about in the following articles:




#3

Hi ramil,

I was thinking more towards the use-case of using ref in this case, if there is any obvious benefit in doing so. Such as if I am rendering multiple Gantt, I can then create ref to each of them so I can get an “instance” of the gantt and then trigger some event on that particular gantt using ref call.

From what I understand, I probably should not be using ref unless necessary. And since not using ref works, then I probably will continue doing so.