Error: Invalid hook call. Hooks can only be called inside of the body of a function component. occurs because the original react-charts example uses React Hooks, which cannot be used inside class components.
Here’s a working class-based version that supports gradient colors for each line/series, using renderSVG and getSeriesStyle.
import React from "react";
import ReactDOM from "react-dom";
import { Chart } from "react-charts";
import jsonData from "./data.json";
class GraphClub extends React.Component {
constructor(props) {
super(props);
this.state = {
data: jsonData,
axes: [
{
primary: true,
type: "ordinal",
position: "bottom"
},
{
type: "linear",
position: "left",
stacked: true
}
]
};
}
getSeriesStyle(series) {
return {
color: `url(#${series.index % 4})`,
opacity: 1
};
}
render() {
const { data, axes } = this.state;
return (
<div style={{ width: "500px", height: "300px" }}>
<Chart
data={data}
axes={axes}
getSeriesStyle={this.getSeriesStyle}
tooltip
renderSVG={() => (
<defs>
<linearGradient id="0" x1="0" x2="0" y1="1" y2="0">
<stop offset="0%" stopColor="#df4081" />
<stop offset="100%" stopColor="#42E695" />
</linearGradient>
<linearGradient id="1" x1="0" x2="0" y1="1" y2="0">
<stop offset="0%" stopColor="#df4081" />
<stop offset="100%" stopColor="#42E695" />
</linearGradient>
<linearGradient id="2" x1="0" x2="0" y1="1" y2="0">
<stop offset="0%" stopColor="#df4081" />
<stop offset="100%" stopColor="#42E695" />
</linearGradient>
<linearGradient id="3" x1="0" x2="0" y1="1" y2="0">
<stop offset="0%" stopColor="#df4081" />
<stop offset="100%" stopColor="#42E695" />
</linearGradient>
</defs>
)}
/>
</div>
);
}
}
export default function App() {
return <GraphClub />;
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Work with our skilled React developers to accelerate your project and boost its performance.
Hire Reactjs Developers