Reputation: 143
I am trying to use a Dygraph in my Reactjs web application but I am unable to implement it. I am completely new with Dygraphs. I tried this demo graph but unable to do it. Website also provides the details regarding HTML and JS based graphs. I am facing issues to integrate it in my React App. Also, I am not getting how to pass data to the graph. Kindly help with this. Thank you for your help !
import React, { Component } from 'react';
import Dygraph from 'dygraphs';
import 'dygraphs/dist/dygraph.min.css'
class DyGraph extends Component {
constructor(props) {
super(props);
const g = new Dygraph('graph',
`Date,A,B
2016/01/01,10,20
2016/07/01,20,10
2016/12/31,40,30
`, {
title: 'Pressure Transient(s)',
titleHeight: 32,
ylabel: 'Pressure (meters)',
xlabel: 'Time',
gridLineWidth: '0.1',
width: 700,
height: 300,
connectSeparatedPoints: true,
axes: { "x": { "axisLabelFontSize": 9 }, "y": { "axisLabelFontSize": 9 } },
labels: ['Date', 'Tampines Ave10 (Stn 40)'],
});
}
render() {
return <div id="graph"></div>;
}
}
export default DyGraph;
I am getting the following error:
Error: Constructing dygraph with a non-existent div!
▶ 2 stack frames were collapsed.
new DyGraph
D:/themesdemo/src/components/DyGraph/index.js:17
14 | // { name: 'Group D', value: 200 },
15 | // ];
16 |
> 17 | const g = new Dygraph('graph',
| ^ 18 | `Date,A,B
19 | 2016/01/01,10,20
20 | 2016/07/01,20,10
Upvotes: 2
Views: 1764
Reputation: 16955
The issue is that the <div>
doesn't exist in the DOM until after the component mounts (the sequence is constructor
then render
then componentDidMount
). If you try creating the graph in componentDidMount
, you'll have better luck:
class DyGraph extends Component {
constructor(props) {
super(props);
}
render() {
return <div id="graph"></div>;
}
componentDidMount() {
const g = new Dygraph('graph', `...`, { /* ... */ });
}
}
If you have more than one chart on the page, you'll need to use a ref.
There is also a react-dygraphs
library you could try, though it hasn't been updated in a few years now.
Upvotes: 1