'How do i use chartjs in react project properly?
Im trying to use chartjs in my react project but it doesnt work. What am i doing wrong?
You can see console logs here:
import styled from "styled-components";
import { Bar } from "react-chartjs-2";
const WeatherChart = () => {
return (
<Container>
<Bar
data={{ labels: ["Red", "Blue"] }}
width={100}
height={50}
options={{ maintainAspectRatio: false }}
/>
</Container>
);
};
const Container = styled.section`
height: 50%;
width: 100%;
display: flex;
align-items: center;
justify-content: center;
`;
export default WeatherChart;
Solution 1:[1]
The attributes you're passing to Bar are incorrect. Specifically, your data attribute is missing its own datasets attribute, as can be seen in the error log when Chart.js is attempting to call setDatasets.
Suppose you're charting the temperature for each day of the past week:
Your labels attribute:
const labels = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
Your data attribute:
const data = {
labels,
datasets: [
{
label: 'Temperatures',
data: labels.map(() => Math.random() * 100),
backgroundColor: 'rgba(255, 99, 132, 0.5)',
},
],
}
Your options attribute:
const options = {
responsive: true,
plugins: {
legend: {
position: 'top',
},
title: {
display: true,
text: 'Chart.js Bar Chart',
},
},
}
Pass them to the Bar:
return <Bar options = {options} data = {data} />
Your chart:
Learn more and see more examples in the docs.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |

