Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Morris.js with reactjs

How can I use reactjs to create a morris.js chart? I am using an Asp.net MVC5 project with react.js library. It is my first react project, and I want to change a morris.js chart when some button clicked. I don't want to use other react library just morris js librayr inside react js script

like image 869
Aggounix Avatar asked Nov 01 '25 10:11

Aggounix


2 Answers

Here's how you can make Morris.js work with React.

  1. Install Morris.js and its dependency - Raphael.js:
npm install --save-dev morris.js
npm install --save-dev raphael
  1. In your component:
import Raphael from 'raphael';
import 'morris.js/morris.css';
import 'morris.js/morris.js';
  1. Morris looks for Raphael to be in global scope
constructor() {
    super();
    window.Raphael = Raphael;
}

Important notes

  1. If you get a compilation error for morris.css, please read this.

  2. If you write import Morris from 'morris.js/morris.js', it won't work.

  3. There's another way to make Raphael be in global scope.

const webpack = require('webpack');
module.exports = {
    plugins: [
        new webpack.ProvidePlugin({
            Raphael: 'raphael'
        })
    ],
    ...
}

If you prefer this variant, you don't need:

import Raphael from 'raphael';
window.Raphael = Raphael;
like image 182
Arsen K. Avatar answered Nov 04 '25 11:11

Arsen K.


Simple solution

In componentDidMount() draw your chart, in my example it's a donut:

yourChart = Morris.Donut({ element: 'elementId', data: data, // ...other options });

where yourChart is declared outside of the class or you can do this.yourChart in the constructor().

If you want to update/redraw your chart, you can call yourChart.setData(newData) at the button click.

like image 37
novasaint Avatar answered Nov 04 '25 11:11

novasaint



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!