简体   繁体   中英

how to use chart.js with react Hook?

I'm trying to make a dashboard with React Js using the hooks the data normally be taken from an APi but to test I put hard values in an array. I get the grid but no value is taken into account. I don't know what I'm doing wrong and also want to know if chart.js is the best choice.

Here the error that I get

index.js:1375 Warning: Failed prop type: Invalid prop `data` supplied to `ChartComponent`.
    in ChartComponent (created by Bar)
    in Bar (at ErrorChart.js:8)
    in div (at ErrorChart.js:7)
    in ErrorChart (at App.js:20)
    in div (at App.js:18)
    in App (at src/index.js:7)
import React, { useState, useEffect } from "react";
import ProgressBar from "./ActivityAlert/ErrorMonitoring/ProgressBar";
import ErrorRanking from "./ActivityChart/ErrorChart/ErrorChart";
import ErrorChart from "./ActivityChart/ErrorChart/ErrorChart";

const App = () => {
  const [percentage, setpercentage] = useState(1);
  const [data, setData] = useState( [])

  useEffect(() => {
    setpercentage(80);

    setData(["12","13","14"])

  }, [setpercentage,setData]);

  return (
    <div>
      {/* <ProgressBar percentage={percentage}  /> */}
      <ErrorChart data= {data} />
    </div>
  );
};

export default App;


import React  from "react";
import {Bar} from 'react-chartjs-2'

const ErrorChart = ({data}) =>{

return (
<div>
    <Bar data={data}>

    </Bar>
</div>
  );

}
export default ErrorChart

I jsut want to display data from this small array

Structure of your data is not valid. You need to pass an object which has to have labels and datasets keys.

A sample data can be found in the documentation.

Instead of ["12", "13", "14] , try passing this object:

{
        labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
        datasets: [{
            label: '# of Votes',
            data: [12, 19, 3, 5, 2, 3],
            backgroundColor: [
                'rgba(255, 99, 132, 0.2)',
                'rgba(54, 162, 235, 0.2)',
                'rgba(255, 206, 86, 0.2)',
                'rgba(75, 192, 192, 0.2)',
                'rgba(153, 102, 255, 0.2)',
                'rgba(255, 159, 64, 0.2)'
            ],
            borderColor: [
                'rgba(255, 99, 132, 1)',
                'rgba(54, 162, 235, 1)',
                'rgba(255, 206, 86, 1)',
                'rgba(75, 192, 192, 1)',
                'rgba(153, 102, 255, 1)',
                'rgba(255, 159, 64, 1)'
            ],
            borderWidth: 1
        }]
    }

Working demo: https://stackblitz.com/edit/react-cdmfuu

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM