I am new to react. So please pardon my naiveness. I have the following piece of react code:
import { Line } from '@antv/g2plot';
const data = [
{ year: '1991', value: 3 },
{ year: '1992', value: 4 },
{ year: '1993', value: 3.5 },
{ year: '1994', value: 5 },
{ year: '1995', value: 4.9 },
{ year: '1996', value: 6 },
{ year: '1997', value: 7 },
{ year: '1998', value: 9 },
{ year: '1999', value: 13 },
];
const linePlot = new Line(document.getElementById('container'), {
title: {
visible: true,
text: 'DEF',
},
description: {
visible: true,
text: 'ABC',
},
padding: 'auto',
forceFit: true,
data,
xField: 'year',
yField: 'value',
smooth: true,
});
linePlot.render();
I need to convert the above piece of code inside a class and export it: I wrote the below code
import React, { useEffect } from "react";
import { Line } from "
@antv
/g2plot";
export const YourComponentName = function() {
const [linePlot, setlinePlot] = useState(initialState);
const data = [
{ year: "1991", value: 3 },
{ year: "1992", value: 4 },
{ year: "1993", value: 3.5 },
{ year: "1994", value: 5 },
{ year: "1995", value: 4.9 },
{ year: "1996", value: 6 },
{ year: "1997", value: 7 },
{ year: "1998", value: 9 },
{ year: "1999", value: 13 }
];
useEffect(() => {
setlinePlot(
new Line(document.getElementById("container"), {
title: {
visible: true,
text: "DEF"
},
description: {
visible: true,
text: "ABC"
},
padding: "auto",
forceFit: true,
data,
xField: "year",
yField: "value",
smooth: true
})
);
return () => {
// you can clanup here
};
}, [linePlot]);
return; //jsx from here with state which you want to render.
};
However since, this is a container class, I don't want "document..getElementById("container")" in my this component class. My index.js already has
ReactDOM.render(<Main />, document.getElementById("container"));
Please help me.
In React you can either have a functional component or a class based component. You have used the react
useStateanduseEffecthooks, which are for functional components only and cannot be used in the class-based approach.Just a side note. This talks about the reasons why you should not update state inside the useEffect hook.
Do you want the Line to be created once, when the component loads?
Another note. The 'below code' you mentioned does not use class's.
*Edit
Here is a basic react implementation, however, due to you using antv/g2plot.Line I can't get it to update the graph without overlaying it on top of the old one. From a quick look at the docs, I would recommend changing it to a Chart.