Reputation: 61
I'm currently trying to render a bar chart in ReactJS using Chart.js
info:
official page - http://www.chartjs.org/docs/
gitHub - https://github.com/reactjs/react-chartjs
The problem I have is that even though my terminal doesn't give me any errors, my local server doesn't render anything.
Here is my code:
var React = require('react');
var BarChart = require('../../node_modules/chart.js/Chart.js');
var styles = require('./Styles.js');
var data={
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
}]
};
var options={
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
};
var Graphs = React.createClass({
render: function() {
return (
<div id='graphDiv'>
<BarChart type='bar' data={data} options={options} />
</div>
);
}
});
module.exports = Graphs;
Please bear with me if I made some silly mistakes, it's the first React app I'm coding so I have a lot to learn.
I have multiple questions, though:
did I install the library at the right place? - I used npm and it is now located in the node_modules folder
Is the path towards the file written correctly? as the gitHub says it should be something like this:
var LineChart = require("react-chartjs").Line;
Is it ok to place the data and the options as global variables?
what's wrong with my code if I don't get any error messages from the terminal ?
Have a nice day
Upvotes: 0
Views: 1886
Reputation: 61
Follow Shubham Khatri's post. Then just change the following:
import {Bar} from 'react-chartjs';
import Chart from 'chart.js';
Into this:
var BarChart = require('react-chartjs').Bar;
var Chart = require('chart.js');
I don't know why but it works.
Upvotes: 0
Reputation: 281616
You are importing Barchart
from the wrong module. you need to import it from BarChart
import {Bar} from 'react-chartjs';
Also you need to include chartjs as dependency
import Chart from 'chart.js';
and then use it as
render: function() {
return (
<div id='graphDiv'>
<Bar type='bar' data={data} options={options} />
</div>
);
}
});
install react-chartjs
as
npm install -S react-chartjs
Also make sure to install and import [email protected]
as a dependency in your project . Install it as
npm install -S chart.js@^1.1.1
Upvotes: 1