0

I am creating an application that shows charts and to load the chart, I need to write the following lines of code:

const line_chart = new GoogleCharts.api.visualization.LineChart(document.getElementById('chart-div'));
line_chart.draw(data, options);

This chart-div is inside another component called <ChartComponent/>. Is it possible to access chart-div without using document.getElementById?

Harish
  • 490
  • 2
  • 11
  • 19

1 Answers1

0

You can use react refs and pass the reference through props.

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.myRef = React.createRef();
  }
  render() {
    return <div ref={this.myRef} />;
  }
}

https://reactjs.org/docs/refs-and-the-dom.html

Mykybo
  • 1,429
  • 1
  • 12
  • 24
  • How do I pass the reference through props? – Harish Jun 13 '19 at 10:36
  • like any other prop: `` – Mykybo Jun 13 '19 at 10:42
  • That will allow us to pass the prop from parent to child not from child to parent. I am checking other SO questions that explain how it is possible. https://stackoverflow.com/questions/38394015/how-to-pass-data-from-child-component-to-its-parent-in-reactjs – Harish Jun 13 '19 at 10:48