React Invalid hook call while using chartJS - javascript

I attempted to add a chartJS line chart to my application and got 'Invalid Hook Call' errors. I figured I might be doing something wrong, so I started a fresh application and attempted to follow a tutorial. After following this VERY basic youtube tutorial for using ChartJS in React, I get a blank page.
If I go to inspect->console. I see errors for 'Invalid Hook Call'.
I have checked both versions of react-native and react-dom; versions do not seem to be the issue. This is my output from npm ls for reference.
My ./App.js code - its literally almost a copy of the tutorial . If i remove the <Bar /> from the return at the bottom, application runs fine. :
import './App.css';
import {
Chart as ChartJS,
CategoryScale,
LinearScale,
BarElement,
Title,
Tooltip,
Legend,
} from 'chart.js'
import { Bar } from 'react-chartjs-2'
import React, {useState, useEffect} from 'react'
ChartJS.register(CategoryScale,
LinearScale,
BarElement,
Title,
Tooltip,
Legend);
function App() {
const [chartData, setChartData] = useState({
datasets: [],
});
const [chartOptions, setChartOptions] = useState({});
useEffect(() => {
setChartData({
labels: ["Greg", "Chuck", "Kevin", "Sam", "Seth"],
datasets: [
{
label: "Votes",
data: [50,1,1,0,1000],
borderColor: "rgb(53, 162, 235)",
backgroundColor: "rgba(53, 162, 235, 0.3)",
},
],
})
setChartOptions({
responsive: true,
plugins: {
legend: {
position: "top",
},
title: {
display: true,
text: "Who does the most work?",
},
},
});
}, []);
return (
<div className="App">
<h2>BarChart</h2>
<Bar options={chartOptions} data={chartData} />
</div>
);
}
export default App;
Does anyone see something I'm not as to why I could be getting this error?

Related

Reactive data with vue-chartjs and Pinia stores

I am new at combining the use of a Pinia store data and vue-chartjs to create reactive charts. I'm using this example as a guide but struggling to have the chart reactive to changes in the store.
I change the Pinia store data in another component using a reactive form, and can see the store data changing, but the chart not updating.
I am rendering a chart with the following component:
<script setup>
import { storeToRefs } from 'pinia'
import { useStore} from '#/store/pinia-store-file';
import {
Chart as ChartJS,
CategoryScale,
LinearScale,
PointElement,
LineElement,
Title,
Tooltip,
Legend
} from 'chart.js';
import { Line } from 'vue-chartjs';
ChartJS.register(
CategoryScale,
LinearScale,
PointElement,
LineElement,
Title,
Tooltip,
Legend
);
const store = useStore();
const storeData= storeToRefs(store);
const labels = [...Array(storeData.arr.value.length).keys()];
const data = {
labels: labels,
datasets: [
{
label: 'Data One',
backgroundColor: '#f87979',
data: storeData.arr.value
}
]
}
const options = {
responsive: true,
maintainAspectRatio: false
}
</script>
<template>
<Line :data="data" :options="options" />
</template>
I've tried wrapping the store variable in ref() but I think I need to re-render the chart? I'm struggling to apply the above example to a Pinia store state and updating when the store is change.
You don't set data as response. Please use computed
This code can solve the problem:
<script setup>
import { storeToRefs } from 'pinia'
import { useStore} from '#/store/pinia-store-file';
import {
Chart as ChartJS,
CategoryScale,
LinearScale,
PointElement,
LineElement,
Title,
Tooltip,
Legend
} from 'chart.js';
import { Line } from 'vue-chartjs';
import { computed } from "vue"
ChartJS.register(
CategoryScale,
LinearScale,
PointElement,
LineElement,
Title,
Tooltip,
Legend
);
const store = useStore();
const storeData= storeToRefs(store);
const data = computed(() => ({
labels: [...Array(storeData.arr.value.length).keys()],
datasets: [
{
label: 'Data One',
backgroundColor: '#f87979',
data: storeData.arr.value
}
]
}))
const options = {
responsive: true,
maintainAspectRatio: false
}
</script>
<template>
<Line :data="data" :options="options" />
</template>

Vue.js: How to retrieve css var under <script>

I'm using chartJs to add a Doughnut chart on my app, but I need to setup it's color under <script> and I'd like to get the color from theme/variables.css .
In the code below, I have a hardcoded backgroundColor, but I'd like to get it from --ion-color-secondary and --ion-color-secondary-contrast instead. How can I achieve that?
Here is the code:
<template>
<Doughnut
:chart-data="chartData"
:chart-options="chartOptions"
/>
</template>
<script lang=ts>
import { defineComponent, PropType } from 'vue'
import { Doughnut } from 'vue-chartjs'
import {
Chart as ChartJS,
Title,
Tooltip,
Legend,
ArcElement,
CategoryScale,
Plugin
} from 'chart.js'
ChartJS.register(Title, Tooltip, Legend, ArcElement, CategoryScale)
export default defineComponent<{fastdata: any}>({
name: 'MrProgress',
components: {
Doughnut
},
inject: ["fastdata"],
setup() {
const chartOptions = {
responsive: true,
maintainAspectRatio: true,
cutout: "90%",
borderWidth: 0,
}
return {
chartOptions,
};
},
computed: {
chartData() {
const pts = this.fastdata.user.pts;
const missing = this.fastdata.user.proximo_nivel - pts;
return {
datasets: [
{
backgroundColor: ['#41B883', '#e4e0d8'],
data: [pts, missing]
}
]
}
}
}
})
</script>
Following the tip from #EstusFlask in the comment regarding userCssVar, I manged to solve it in the following way:
npm i #vueuse/core
...
import { useCssVar } from '#vueuse/core'
import { ref } from 'vue'
<script>
...
const color_pts = useCssVar(ref('--ion-color-secondary'), ref(null)).value;
const color_missing = useCssVar(ref('--ion-background-color'), ref(null)).value;
return {
datasets: [
{
backgroundColor: [color_pts, color_missing],
data: [pts, missing]
}
]
}
...
</script>

How to use react-leaflet-pixi-overlay

Im trying to implement the minimal example of the docs of react-leaflet-pixi-overlay. You can find the code below:
import React from "react";
import PixiOverlay from "react-leaflet-pixi-overlay";
import { Map, TileLayer } from "react-leaflet";
import { renderToString } from "react-dom/server";
import ReactDOM from "react-dom";
const App = () => {
const markers = [
{
id: "randomStringOrNumber",
iconColor: "red",
position: [-37.814, 144.96332],
popup: renderToString(<div>All good!</div>),
onClick: () => alert("marker clicked"),
tooltip: "Hey!"
},
{
id: "2",
iconColor: "blue",
position: [-37.814, 144.96332],
popup: "Quack!",
popupOpen: true, // if popup has to be open by default
onClick: () => alert("marker clicked"),
tooltip: "Nice!"
}
];
return (
<Map
preferCanvas={true}
maxZoom={20}
minZoom={3}
center={[-37.814, 144.96332]}
// Other map props...
>
<TileLayer
url="https://{s}.basemaps.cartocdn.com/rastertiles/voyager/{z}/{x}/{y}{r}.png"
attribution='© OpenStreetMap contributors'
/>
<PixiOverlay markers={markers} />
</Map>
);
};
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
I have implemented it in the following sandbox, but doesnt work:
_reactLeaflet.useLeaflet is not a function
Cant find any example on the internet.
Made it work using following versions:
leaflet 1.3.4
react 16.14.0
react-dom 16.14.0
react-leaflet 2.8.0
react-leaflet-pixi-overlay 1.0.10
react-scripts 1.1.4
Check the sandbox working

Chart js in React/Gatsby

Hello I am trying to use chart js in Gatsby. I am currently following a tutorial for using chart js with react and I am not sure if the issue is that he is using creat-react-app and not Gatsby, but the errors do not seem to indicate that.
first I installed the following:
npm i --save react-chartjs-2
then
npm i --save chart.js
chartData.js:
import React, {useState, useEffect } from "react";
import { Line } from "react-chartjs-2";
const chartData = () => {
const [chartData, setChartData] = useState({});
const chart = () => {
setChartData({
labels: ["monday", "tuesday", "wednesday", "thursday", "friday"],
datasets: [
{
level: 'level of xyz',
data: [32, 55, 33, 47, 64]
}
]
})
}
useEffect(() => {
chart()
}, [])
return(
<div>
<h1>Hello</h1>
<div>
<Line data={chartData}/>
</div>
</div>
)
}
export default chartData;
I am getting these erros:
6:39 error React Hook "useState" is called in function "chartData" which is neither a React function component or a custom React Hook function react-hooks/rules-of-hooks
20:5 error React Hook "useEffect" is called in function "chartData" which is neither a React function component or a custom React Hook function react-hooks/rules-of-hooks
You have a name cohersion issue. Try renaming the functions and variables with a diferent name:
import React, { useState, useEffect } from "react";
import { Line } from "react-chartjs-2";
const ChartData = () => {
const [whatever, setWhatever] = useState({});
const chart = () => {
setWhatever({
labels: ["monday", "tuesday", "wednesday", "thursday", "friday"],
datasets: [
{
level: 'level of xyz',
data: [32, 55, 33, 47, 64]
}
]
})
}
useEffect(() => {
chart()
}, [])
return(
<div>
<h1>Hello</h1>
<div>
<Line data={whatever}/>
</div>
</div>
)
}
export default ChartData;
In your previous code:
const chartData = () => {
const [chartData, setChartData] = useState({});
...
}
Where chartData is duplicated causing the error.
In addition, your chartData must be ChartData since, in React, the components must be capitalized.
You need to capitalize the name of the component. Right now you are setting the component to chartData, and then defining chartData as a hook. Change the component to ChartData.js

ReactJS + Material Design: How to get theme colors outside component?

In my ReactJS app.js I defined a theme:
const theme = createMuiTheme({
palette: {
primary: {
main: "#54BD40",
},
},
});
I am using the React wrapper for Chart.js and I want to set-up a chart graph. But I am not sure how I can use the primary/main color from my theme:
import React, { Component } from 'react';
import { Line } from 'react-chartjs-2';
let data = []; //data here
const MONTHS = ['Jan', 'Feb', 'Mrt', ...];
const WEEK = ['Sun', 'Mon', 'Tue', ...];
let chart = {
labels: MONTHS,
datasets:[{
borderColor: ['#XXX'], //THEME COLOR HERE
}],
};
class LineChart extends Component{
constructor(props){
super(props);
this.state = {
chartData: chart,
usage: false,
generation: true,
}
}
render(){
return (
<div>
<Line data={ this.state.chartData } options={} />
</div>
)
}
}
export default LineChart;
For using theme palettes inside render(), I know I can import withTheme() and use this.props.theme. But how this work now outside the component? (I just started using ReactJS)
Well as I understand you can import constant into your main js file after doing
export in app.js. Example. -
export const theme = createMuiTheme({ palette: { primary: { main: "#54BD40", }, }, });
Then import
Import { theme } from "app"
And use it anywhere in your main js file.

Categories

Resources