ReferenceError: ResizeObserver is not defined with nivo and NextJS - reactjs

I want to use nivo with Next but when I load the page containing a pie chart made with nivo, I get this error: ReferenceError: ResizeObserver is not defined.
My Pie.js component:
import { ResponsivePie } from "#nivo/pie";
export const data = [
{
id: "c",
label: "c",
value: 80,
color: "hsl(8, 70%, 50%)",
},
{
id: "lisp",
label: "lisp",
value: 188,
color: "hsl(122, 70%, 50%)",
},
{
id: "go",
label: "go",
value: 161,
color: "hsl(111, 70%, 50%)",
},
];
export default function MyPie({ data }) {
return (
<ResponsivePie
data={data}
margin={{ top: 40, right: 80, bottom: 80, left: 80 }}
innerRadius={0.5}
padAngle={0.7}
cornerRadius={3}
activeOuterRadiusOffset={8}
borderWidth={1}
borderColor={{ from: "color", modifiers: [["darker", 0.2]] }}
arcLinkLabelsSkipAngle={10}
arcLinkLabelsTextColor="#333333"
arcLinkLabelsThickness={2}
arcLinkLabelsColor={{ from: "color" }}
arcLabelsSkipAngle={10}
arcLabelsTextColor={{ from: "color", modifiers: [["darker", 2]] }}
defs={[
{
id: "dots",
type: "patternDots",
background: "inherit",
color: "rgba(255, 255, 255, 0.3)",
size: 4,
padding: 1,
stagger: true,
},
{
id: "lines",
type: "patternLines",
background: "inherit",
color: "rgba(255, 255, 255, 0.3)",
rotation: -45,
lineWidth: 6,
spacing: 10,
},
]}
/>
)
};
My chart.js page:
import MyPie, { data } from "../components/Pie";
import homeStyles from "../styles/Home.module.css";
function Chart() {
return (
<div className={homeStyles.divchart}>
<MyPie data={data}/>
</div>
);
};
export default Chart;
This error only appears when using ResponsivePie and not Pie. I also tried to make it work with a React project but though I don't get this error, Nothing seems to be displayed.
Edit:
After some investigations, it looks like there is something wrong with #nivo/core 0.79.0 dependency. We should open an issue on the GitHub repo. I made some changes to check whether it is caused by my version of Next.js but the bug occurs only with #nivo/core 0.79.0.

It turns out this was the result of a bug introduced in version 0.79.0, which was fixed in https://github.com/plouc/nivo/pull/1886.
You should update #nivo/core to 0.79.1.
It looks like #nivo/pie is not compatible with Next.js server-side rendering as it utilizes Web APIs (ResizeObserver).
To avoid importing MyPie (and subsequently ResponsivePie) on the server, you can dynamically import it on the client-side only using next/dynamic with ssr: false.
import dynamic from "next/dynamic";
import { data } from "../components/Pie";
import homeStyles from "../styles/Home.module.css";
const MyPie = dynamic(() => import("../components/Pie"), {
ssr: false
})
function Chart() {
return (
<div className={homeStyles.divchart}>
<MyPie data={data}/>
</div>
);
};
export default Chart;

It's likely that code is being run on server side (SSR), and ResizeObserver doesn't exist there. You should try to make sure that your code only executes when on client side.
It's hard for me to tell you how as I don't know what your setup is. You can likely just add a check to only run that part of the code if ResizeObserver is defined.
I hope at least this points you in the right direction.

Related

React Js Plotly Remove Time Gaps In Graph

I am trying to plot stock data, but there are gaps in the graph where data for these time periods don't exist. How do I remove these gaps? I found that there is an update_xaxes function but I'm not sure how to apply it to my case.
My code:
import React, { useState, Component, useEffect } from "react";
import Plot from 'react-plotly.js';
export const Chart = () => {
return (
<div>
<Plot
data={[
{
x: data['dates'],
y: data['open_price'],
type: 'scatter'
}
]}
layout={{
autosize: false,
width: 1500,
height: 800,
xaxis: {
color: 'red',
rangebreaks: {
bounds: ["sat", "mon"],
values: ["2015-12-25", "2016-01-01"],
bounds: [17, 9], pattern: "hour"
}
}
}}
/>
</div>
)
}
react-ploty allows configuring the underlying ploty configuration through props. The data props you're already using accepts the same Traces Object than regular ploty. Therefore you can use rangebreaks as suggested by #r-beginners to achieve the desired effect.
xaxis: {
color: 'red',
rangebreaks: [
{ bounds: ["sat", "mon"] },
{
values: ["2019-12-25"]
},
{ bounds: [17, 9], pattern: "hour" }
]
}
I fixed it by making rangebreaks an array.

react-chartjs-2 options are not recognized for Bars

I am trying to built a barchart component via "react-chartjs-2". I did pretty much paste my code from here: https://www.c-sharpcorner.com/article/create-different-charts-in-react-using-chart-js-library/.
This is how it looks:
import React from 'react';
import {Bar} from "react-chartjs-2";
const BarChart = () => {
const barChartData = {
labels: ["October", "November", "December"],
datasets: [
{
data: [8137119, 9431691, 10266674],
label: "Infected People",
borderColor: "#3333ff",
backgroundColor: "#547db4",
fill: true
},
{
data: [1216410, 1371390, 1477380],
label: "Deaths People",
borderColor: "#ff3333",
backgroundColor: "#f7813e",
fill: true
}
]
};
const barChart = (
<Bar
type="bar"
width={130}
height={50}
options={{
title: {
display: true,
text: "COVID-19 Cases of Last 3 Months",
fontSize: 15
},
legend: {
display: true, //Is the legend shown?
position: "bottom" //Position of the legend.
}
}}
data={barChartData}
/>
);
return barChart;
};
export default BarChart
Everything seems to be working fine, besides the fact that the options prop is not being recognized by the code.
Did anyone come across a similar issue and can help me out?
Update options prop as bellow.
options = {{
plugins: {
title: {
display: true,
text: "COVID-19 Cases of Last 3 Months"
},
legend: {
display: true,
position: "bottom"
}
}
}}

I want to change the position and style of the label in the React chart

I am using react-chartjs-2. I want to display the position of the label below the graph. Also, the shape of the label is currently square, but I would like to change it to a round shape. I specified option and position: bottom, but the position of the label did not change.
import "./styles.css";
import React from "react";
import { Bar } from "react-chartjs-2";
const data = [
{
label: "a",
data: [56, 23, 55, 56, 57]
},
{
label: "b",
data: [22, 17, 32, 47, 62]
},
{
label: "c",
data: [46, 73, 25, 76, 27]
}
];
const App = () => {
const CHART_COLORS = ["#e35b2c", "#e77235", "#eb8a40"];
const list = data.map((d, index) => {
return {
label: d.label,
backgroundColor: CHART_COLORS[index],
data: d.data,
stack: 1
};
});
const options = {
legend: {
position: "bottom"
}
};
return (
<>
<div className="App">
<Bar
data={{
labels: ["block1", "block2", "block3"],
datasets: list
}}
width={100}
height={50}
options={options}
/>
</div>
</>
);
};
export default App;
Legend option is changed in latest version of chartjs to,
Namespace: options.plugins.legend
plugins: {
legend: {
position: "bottom",
labels: {
usePointStyle: true //for style circle
}
}
}
};
You can check working demo here, https://codesandbox.io/s/react-chartjs-legend-option-prbgb
Reference : https://www.chartjs.org/docs/latest/configuration/legend.html

Could not find a declaration file for module chartjs-plugin-stacked100

I am trying to use chartjs-plugin-stacked100 in a React App:
import React, { useEffect, useState } from 'react';
import { Chart } from 'react-chartjs-2';
import ChartjsPluginStacked100 from 'chartjs-plugin-stacked100';
const ConnectedTime = () => {
// https://designcode.io/react-hooks-handbook-usestate-hook
// https://designcode.io/react-hooks-handbook-fetch-data-from-an-api
useEffect(() => { }, []);
return <>
{
<div>
<ChartjsPluginStacked100
type="bar"
data={{
labels: ["Foo", "Bar"],
datasets: [
{ label: "bad", data: [5, 25], backgroundColor: "rgba(244, 143, 177, 0.6)" },
{ label: "better", data: [15, 10], backgroundColor: "rgba(255, 235, 59, 0.6)},
{ label: "good", data: [10, 8], backgroundColor: "rgba(100, 181, 246, 0.6)" }]
}}
options={{
indexAxis: "y",
plugins: {
stacked100: { enable: true }
}
}} />
</div>
}
</>
}
export default ConnectedTime
When I yarn start this piece of code, I get the error:
TypeScript error in /home/mihamina/.../src/Components/ConnectedTime/ConnectedTime.tsx(4,37):
Could not find a declaration file for module 'chartjs-plugin-stacked100'.
'/home/mihamina/.../node_modules/chartjs-plugin-stacked100/build/index.js' implicitly has an 'any' type.
Try `npm i --save-dev #types/chartjs-plugin-stacked100` if it exists
or add a new declaration (.d.ts) file containing
`declare module 'chartjs-plugin-stacked100';`
Issuing npm i --save-dev #types/chartjs-plugin-stacked100 : The package does not exist.
I dont quite understand about the .d.ts file:
Do I create it at the root of the project? (same folder as package.json?)
Is the required name really .d.ts or should I prepend the name with chartjs-plugin-stacked100?
I managed to make it work:
Create a global.d.ts and declare the module
Use the Bar component
Content of global.d.ts:
declare module 'chartjs-plugin-stacked100';
declare module 'chartjs-plugin-stacked100'{
export function ChartjsPluginStacked100(): function
}
Use of Bar:
import { Chart, Bar } from 'react-chartjs-2';
import ChartjsPluginStacked100 from 'chartjs-plugin-stacked100';
Chart.register(ChartjsPluginStacked100);
const ChartData = (props: any) => {
return <>
{
<div>
<Bar
data={{
labels: ["Foo", "Bar"],
datasets: [
{ label: "bad", data: [5, 25], backgroundColor: "rgba(244, 143, 177, 0.6)" },
{ label: "better", data: [15, 10], backgroundColor: "rgba(255, 235, 59, 0.6)" },
{ label: "good", data: [10, 8], backgroundColor: "rgba(100, 181, 246, 0.6)" }]
}}
options={{
indexAxis: "y",
plugins: {
stacked100: { enable: true }
}
}} />
</div>
}
</>
};
export default ChartData
I updated the documentation and requested a pull at: https://github.com/y-takey/chartjs-plugin-stacked100/pull/48 , where I wrote a small sample React app that uses the plugin.

How to use chartjs-plugin-trendline with react-chartjs-2

I want to add 'Trend' line to my line chart. I am using react-chartjs-2 to draw charts on my website. The code looks like:
import { Line } from 'react-chartjs-2';
import trendlineLinear from 'chartjs-plugin-trendline';
const PatientInfectionChart = ({ data, labels }) => {
const datasets = [
{
data: data.totalInfected,
backgroundColor: 'rgb(233, 85, 0)',
borderColor: 'rgba(233, 85, 0, 0.7)',
label: 'Today Infected',
},
{
data: data.todayRecovered,
backgroundColor: 'rgb(23, 198, 113)',
borderColor: 'rgba(23, 198, 113, 0.7)',
label: 'Today Recovered',
trendlineLinear: {
style: 'rgb(23, 198, 113)',
lineStyle: 'dotted',
width: 2,
},
},
];
return (
<Line
data={{ datasets, labels }}
plugins={[trendlineLinear]}
options={{
maintainAspectRatio: false,
scales: {
y: {
beginAtZero: true,
},
},
}}
/>
);
};
export default PatientInfectionChart;
However, I get the following error:
Uncaught TypeError: Cannot read property 'ctx' of undefined
at Object.afterDraw (chartjs-plugin-trendline.js:23)
at callback (helpers.segment.js:89)
at PluginService._notify (chart.esm.js:4737)
at PluginService.notify (chart.esm.js:4724)
at Chart.notifyPlugins (chart.esm.js:5788)
at Chart.draw (chart.esm.js:5537)
at chart.esm.js:66
at Map.forEach (<anonymous>)
at Animator._update (chart.esm.js:44)
at chart.esm.js:34
How to I fix this?
The trendline plugin requires chart.js version 2, react chart.js uses version 3 so you will need to downgrade react-chartjs
Commands:
yarn remove react-chartjs-2
yarn add react-chartjs-2#2.11.2

Resources