React components for Chart.js, the most popular charting library

Overview

react-chartjs-2

Logo

React components for Chart.js, the most popular charting library.

Supports Chart.js v3 and v2.

version downloads license


Quickstart   •   Docs   •   Slack   •   Stack Overflow

Quickstart

Install this library with peer dependencies:

npm install --save react-chartjs-2 chart.js

We recommend using [email protected]^3.0.0.

Then, import and use individual components:

import { Doughnut } from 'react-chartjs-2';

<Doughnut data={...} />

Need an API to fetch data? Consider Cube, an open-source API for data apps.

Docs

License

MIT Licensed Copyright (c) 2020 Jeremy Ayerst

Comments
  • Re-rendering plot when any state of the component changes

    Re-rendering plot when any state of the component changes

    This behaviour was not observed with older version of chartjs. i.e version less than 3. When ever the state of the component changes , entire plot re renders again as if it is rendering for the first time. sample code to this behaviour is here

    opened by vaasu070 49
  • chart not updating

    chart not updating

    I'm trying to get my chart to update dynamically as new data comes in (from socket.io) so I have a method onChange(data) that is used as the callback function of setState called when the new data comes in.

    The Chart however does not update itself... unless I refresh/resize the browser. If I set redraw={true}, then the chart updates but it seems to refresh the whole page (?) and kills the performance for the rest of the page...

    Any idea what I'm doing wrong here?

    import React from 'react'
    import ReactDOM from 'react-dom'
    
    import {Line} from 'react-chartjs-2'
    
    module.exports =  class MyChart extends React.Component {
    
      constructor(props)
      {
          super(props)
          this.buffersize
    
          this.data = {
            labels: [],
            datasets: [
              {/
                label: 'My Chart',
                data: []
              }
            ]
          }
    
      }
    
      onChange(newdata) {
    
        const size = this.data.datasets[0].data.length
        if (size >= this.buffersize)
        {
          this.data.datasets[0].data.shift()
          this.data.labels.shift()
        }
    
        this.data.labels.push(newdata.label)
        this.data.datasets[0].data.push(newdata.value)
    
      }
    
      render()
      {
        return (
          <Line data={this.data}/>
        )
      }
    
    }
    
    opened by dmichel76 44
  • Defaults creating error

    Defaults creating error

    I'm trying to use the { defaults } provided by your wrapper but when I pass these into a I get all kinds of errors. (I am not yet modifying these defaults)

    My Code

    import { Bar, defaults } from 'react-chartjs-2';
    
    // component level
    <Bar redraw data={this.props.chartData} height={300} options={defaults} />
    

    Error in console

    core.controller.js:443 Uncaught TypeError: Cannot set property '_data' of undefined
        at Chart.Controller.update (core.controller.js:443)
        at Chart.Controller.resize (core.controller.js:306)
        at eval (core.controller.js:224)
        at eval (core.helpers.js:982)
    update @ core.controller.js:443
    resize @ core.controller.js:306
    (anonymous) @ core.controller.js:224
    (anonymous) @ core.helpers.js:982
    scale.radialLinear.js:113 Uncaught (in promise) TypeError: Cannot read property 'callback' of undefined
        at ChartElement.convertTicksToLabels (scale.radialLinear.js:113)
        at ChartElement.update (core.scale.js:94)
        at getMinimumBoxSize (core.layoutService.js:144)
        at Object.helpers.each (core.helpers.js:23)
        at Object.update (core.layoutService.js:155)
        at Chart.Controller.updateLayout (core.controller.js:381)
        at Chart.Controller.initialize (core.controller.js:250)
        at new Chart.Controller (core.controller.js:231)
        at new Chart (core.js:7)
        at ChartComponent.renderChart (index.js:212)
    

    Version Chartjs: v2.4.0

    opened by nealoke 40
  • Import plugin

    Import plugin

    Is it possible to integrate a plugin into react-chartjs? For example https://github.com/xch89820/Chart.Funnel.js

    I tried using

    Chart.pluginService.register({
    		// something
    	});
    

    with no success.

    Awaiting Feedback 
    opened by DennisKo 32
  • Testing with jest / enzyme / jsdom - Failed to create chart: can't acquire context from the given item

    Testing with jest / enzyme / jsdom - Failed to create chart: can't acquire context from the given item

    Using the DoughnutChart example

    doughnutChart.js

    import React from 'react'
    import { Doughnut } from 'react-chartjs-2'
    
    const data = {
      labels: [
        'Red',
        'Green',
        'Yellow',
      ],
      datasets: [{
        data: [
          300,
          50,
          100,
        ],
        backgroundColor: [
          '#FF6384',
          '#36A2EB',
          '#FFCE56',
        ],
        hoverBackgroundColor: [
          '#FF6384',
          '#36A2EB',
          '#FFCE56',
        ],
      }],
    }
    
    const DoughnutChart = props => (
      <div className="chart-wrapper">
        <Doughnut
          data={data}
        />
      </div>
    )
    
    export default DoughnutChart
    

    doughnutChart.spec.js

    import React from 'react'
    
    import DoughnutChart from './doughnutChart'
    
    it('Renders a DoughnutChart', () => {
      const wrapper = mount(
        <DoughnutChart />,
      )
      expect(wrapper).toMatchSnapshot()
    })
    

    Error

    Failed to create chart: can't acquire context from the given item
          
          at CustomConsole.Object.<anonymous>.console.error (tools/jestSetup.js:37:9)
          at Chart.construct (node_modules/chart.js/src/core/core.controller.js:116:13)
          at new Chart (node_modules/chart.js/src/core/core.js:7:8)
          at ChartComponent.renderChart (node_modules/react-chartjs-2/lib/index.js:259:29)
          at ChartComponent.componentDidMount (node_modules/react-chartjs-2/lib/index.js:81:12)
          at node_modules/react-dom/lib/ReactCompositeComponent.js:264:25
          at measureLifeCyclePerf (node_modules/react-dom/lib/ReactCompositeComponent.js:75:12)
          at node_modules/react-dom/lib/ReactCompositeComponent.js:263:11
          at CallbackQueue.notifyAll (node_modules/react-dom/lib/CallbackQueue.js:76:22)
          at ReactReconcileTransaction.close (node_modules/react-dom/lib/ReactReconcileTransaction.js:80:26)
          at ReactReconcileTransaction.closeAll (node_modules/react-dom/lib/Transaction.js:209:25)
          at ReactReconcileTransaction.perform (node_modules/react-dom/lib/Transaction.js:156:16)
          at batchedMountComponentIntoNode (node_modules/react-dom/lib/ReactMount.js:126:15)
          at ReactDefaultBatchingStrategyTransaction.perform (node_modules/react-dom/lib/Transaction.js:143:20)
          at Object.batchedUpdates (node_modules/react-dom/lib/ReactDefaultBatchingStrategy.js:62:26)
          at Object.batchedUpdates (node_modules/react-dom/lib/ReactUpdates.js:97:27)
          at Object._renderNewRootComponent (node_modules/react-dom/lib/ReactMount.js:319:18)
          at Object._renderSubtreeIntoContainer (node_modules/react-dom/lib/ReactMount.js:401:32)
          at Object.render (node_modules/react-dom/lib/ReactMount.js:422:23)
          at Object.renderIntoDocument (node_modules/react-dom/lib/ReactTestUtils.js:91:21)
          at renderWithOptions (node_modules/enzyme/build/react-compat.js:200:24)
          at new ReactWrapper (node_modules/enzyme/build/ReactWrapper.js:94:59)
          at mount (node_modules/enzyme/build/mount.js:19:10)
          at Object.<anonymous> (src/elements/doughnutChart/doughnutChart.spec.js:6:17)
              at Promise (<anonymous>)
          at Promise.resolve.then.el (node_modules/p-map/index.js:42:16)
              at <anonymous>
    
    opened by csi-lk 28
  • Seamless animation between changed data point values doesn't work

    Seamless animation between changed data point values doesn't work

    When updating the data of the chart instance, you replace all of it which makes chart.js re-render the chart even though you've only updated the data points. This makes it impossible to animate between changed values.

    It would be great if when we only update data points that it would update them them properly so that seamless animation between point values work as intended.

    opened by mekwall 24
  • TypeError: Cannot read properties of undefined

    TypeError: Cannot read properties of undefined

    I am getting the following errors:

    TypeError: Cannot read properties of undefined (reading 'visible')

    where the error references the following line and function:

    _getSortedDatasetMetas(filterVisible) {
         const me = this;
         const metasets = me._sortedMetasets;
         const result = [];
         let i, ilen;
         for (i = 0, ilen = metasets.length; i < ilen; ++i) {
           const meta = metasets[i];
           if (!filterVisible || meta.visible) { <---- THIS LINE
             result.push(meta);
           }
         }
         return result;
        }
    

    TypeError: Cannot read properties of undefined (reading 'controller')

    where the error references the following line:

    const style = meta.controller.getStyle(usePointStyle ? 0 : undefined);

    The problem is that it happens randomly and I can not find any culprit for the problem.

    opened by acceh 22
  • defaults = _chart[

    defaults = _chart["defaults"].defaults is undefined

    Hi and greattings, i maked a project in cube.js and afther that a "dashboard-app" of type 'real time dashboard' everything is ok until I run the app and response whit that message:

    TypeError: _chart.default is undefined

    and i could't advanced afther that.

    so i goes to the file node_modules/react-chartjs-2/es/index.js:644 and I make a log of the variable '_chart' and I see that only exist the field "_chart["default"]"

    so i fix the error whit this:

    // I change this:
    // var defaults = _chart["default"].defaults;
    // For this:
    var defaults = _chart["defaults"];
    

    I hope someone can fix this or use that issue for help

    opened by DiegoCampaneroNegrete 19
  • Serious resize issue if custom size is specified

    Serious resize issue if custom size is specified

    Whenever there is a resize of the canvas element, such as if the user resizes their browser window, and there is a custom size specified on the chart, the chart grows in vertical height. Chart.js itself does not seem to have this issue.

    To see an example, try the samples page, http://jerairrest.github.io/react-chartjs-2/, and watch the "Bar Example (custom size)" sample. Each time you resize the browser window, the chart will grow in vertical height.

    In my own project, the chart will go into an infinite loop and grow until the browser runs out of memory, though this doesn't happen on the sample page. I suppose the chartjs-size-monitor is the culprit since I don't see my component rerendering.

    bug Reproducable 
    opened by domehead100 19
  • Charts not rendering in IE

    Charts not rendering in IE

    I've included the latest versions 2.0.5 in my project and in IE the charts are failing to render. Chrome and FF are fine. On your demo page the charts also don't render in IE. I have looked through the issues which start this is fixed but this doesn't seem to be the case. I have downloaded the latest code and run it and in IE I get the .assign issue. Downloading the zipped code and trying to run the npm install fails as well.

    bug 
    opened by dyarwood 19
  • How to create custom legend?

    How to create custom legend?

    How would one use the legendCallback method with this wrapper? The Chart.js docs show the function returning an HTML string, which is of course not the React way.

    Thank you for your assistance!

    opened by mocon 19
  • [Bug]: Doughnut Chart size is decreasing automatically when mouse hover

    [Bug]: Doughnut Chart size is decreasing automatically when mouse hover

    Would you like to work on a fix?

    • [X] Check this if you would like to implement a PR, we are more than happy to help you go through the process.

    Current and expected behavior

    I used 2 Doughnut charts in my react app with javascript. const stamina_data = { datasets: [ { label: "%", data: [5, 30], backgroundColor: ["#f83472", "#4c565d"], borderColor: ["rgba(255, 99, 132, 1)", "rgba(54, 162, 235, 1)"], borderWidth: 0, }, ], }; const power_data = { datasets: [ { label: "boost", data: [40], backgroundColor: ["#f83472"], borderColor: ["rgba(255, 99, 132, 1)"], borderWidth: 0, }, ], }; <Doughnut data={stamina_data} />

    The issue happened with another developer who checked the chart when the mouse hovered over the chart. He asked me why the charts go decreased sometimes and I tried. But It was working on my side and others' side too. With some problem, I tried zooming in and out of the website. All other cases are working but at zoom 90%, the issue happened to me too.

    Auto decrease happening cases.

    1. Zoom change from 80% to 90%, 100% to 90%.
    2. Mouse hover when zoom is 90%
    3. Any size change events make the chart decrease.

    Reproduction

    Not sure How can I do this

    chart.js version

    ^4.0.1

    react-chartjs-2 version

    ^5.0.1

    Possible solution

    No response

    bug 
    opened by WowDarkHole 0
  • chore(deps): update dependency chartjs-plugin-zoom to v2

    chore(deps): update dependency chartjs-plugin-zoom to v2

    Mend Renovate

    This PR contains the following updates:

    | Package | Change | Age | Adoption | Passing | Confidence | |---|---|---|---|---|---| | chartjs-plugin-zoom | ^1.2.1 -> ^2.0.0 | age | adoption | passing | confidence |


    Release Notes

    chartjs/chartjs-plugin-zoom

    v2.0.0

    Compare Source

    Essential Links

    Breaking Changes

    • #​658 Replace overScaleMode with more flexible scaleMode

    Enhancements

    • #​672 Allow canceling drag-to-zoom on Escape key
    • #​680 Add drawTime option to zoom drag configuration
    • #​695 add-v4-compatibility
    • #​671 Only drag zoom on left mouse button
    • #​659 Export zoomRect and make it more configurable
    • #​658 Replace overScaleMode with more flexible scaleMode

    Thanks to @​LeeLenaleee, @​dependabot, @​dependabot[bot], @​joshkel, @​kurkle and @​stockiNail

    v1.3.0

    Compare Source


    Configuration

    📅 Schedule: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

    🚦 Automerge: Disabled by config. Please merge this manually once you are satisfied.

    Rebasing: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

    🔕 Ignore: Close this PR and you won't be reminded about this update again.


    • [ ] If you want to rebase/retry this PR, check this box

    This PR has been generated by Mend Renovate. View repository job log here.

    opened by renovate[bot] 1
  • [Bug]:

    [Bug]:

    Would you like to work on a fix?

    • [ ] Check this if you would like to implement a PR, we are more than happy to help you go through the process.

    Current and expected behavior

    I am using Remix Run and wanted to add a simple bar chart using chart.js/react-chartjs-2 into my route: import { Bar } from "react-chartjs-2":

    const data = {
      labels: ["January", "February", "March", "April", "May", "June", "July"],
      datasets: [
        {
          label: "My First dataset",
          backgroundColor: "rgba(255,99,132,0.2)",
          borderColor: "rgba(255,99,132,1)",
          borderWidth: 1,
          hoverBackgroundColor: "rgba(255,99,132,0.4)",
          hoverBorderColor: "rgba(255,99,132,1)",
          data: [65, 59, 80, 81, 56, 55, 40],
        },
      ],
    };
    
    export default function Chart() {
      return (
        <>
          <div>
            <h2>Bar Example (custom size)</h2>
            <Bar
              data={data}
              width={100}
              height={50}
              options={{
                maintainAspectRatio: false,
              }}
            />
          </div>
        </>
      );
    }
    

    This error was given when building the page:

    The path "react-chartjs-2" is imported in ..\chart.tsx but "react-chartjs-2" was not found in your node_modules. Did you forget to install it?

    When go to the route page on the browser, this error was given:

    Error: No "exports" main defined in ..\node_modules\react-chartjs-2\package.json
         at new NodeError (node:internal/errors:393:5)
         at throwExportsNotFound (node:internal/modules/esm/resolve:358:9)
         at packageExportsResolve (node:internal/modules/esm/resolve:612:7)
         at resolveExports (node:internal/modules/cjs/loader:529:36)
         at Function.Module._findPath (node:internal/modules/cjs/loader:569:31)
         at Function.Module._resolveFilename (node:internal/modules/cjs/loader:981:27)
         at Function.Module._load (node:internal/modules/cjs/loader:841:27)
         at Module.require (node:internal/modules/cjs/loader:1061:19)
         at require (node:internal/modules/cjs/helpers:103:18)
         at Object.<anonymous> (..\chart.tsx:2:21)
         at Module._compile (node:internal/modules/cjs/loader:1159:14)
         at Object.Module._extensions..js (node:internal/modules/cjs/loader:1213:10)
         at Module.load (node:internal/modules/cjs/loader:1037:32)
         at Function.Module._load (node:internal/modules/cjs/loader:878:12)
         at Module.require (node:internal/modules/cjs/loader:1061:19)
         at require (node:internal/modules/cjs/helpers:103:18)
    

    Reproduction

    Simply create a new Remix project and change the code in the route app\index.tsx as given above.

    chart.js version

    v4.0.1

    react-chartjs-2 version

    v5.0.1

    Possible solution

    No response

    bug 
    opened by zerot69 6
  • fix(deps): update dependency docusaurus-plugin-react-docgen-typescript to v1

    fix(deps): update dependency docusaurus-plugin-react-docgen-typescript to v1

    Mend Renovate

    This PR contains the following updates:

    | Package | Change | Age | Adoption | Passing | Confidence | |---|---|---|---|---|---| | docusaurus-plugin-react-docgen-typescript | ^0.1.0 -> ^1.0.0 | age | adoption | passing | confidence |


    Release Notes

    atomicpages/docusaurus-plugin-react-docgen-typescript

    v1.0.2

    Compare Source

    v1.0.1

    Compare Source

    Bug Fixes

    v1.0.0

    Compare Source

    ⚠ BREAKING CHANGES
      • upgrade to react-docgen-typescript v2
    • rework exports
    Features
    • upgrade to react-docgen-typescript v2 (d34c6e2)
    Bug Fixes

    Configuration

    📅 Schedule: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

    🚦 Automerge: Disabled by config. Please merge this manually once you are satisfied.

    Rebasing: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

    🔕 Ignore: Close this PR and you won't be reminded about this update again.


    • [ ] If you want to rebase/retry this PR, check this box

    This PR has been generated by Mend Renovate. View repository job log here.

    opened by renovate[bot] 2
  • chore(deps): update dependency eslint-config-standard to v17

    chore(deps): update dependency eslint-config-standard to v17

    Mend Renovate

    This PR contains the following updates:

    | Package | Change | Age | Adoption | Passing | Confidence | |---|---|---|---|---|---| | eslint-config-standard | ^16.0.3 -> ^17.0.0 | age | adoption | passing | confidence |


    Release Notes

    standard/eslint-config-standard

    v17.0.0

    Compare Source


    Configuration

    📅 Schedule: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

    🚦 Automerge: Disabled by config. Please merge this manually once you are satisfied.

    Rebasing: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

    🔕 Ignore: Close this PR and you won't be reminded about this update again.


    • [ ] If you want to rebase/retry this PR, check this box

    This PR has been generated by Mend Renovate. View repository job log here.

    opened by renovate[bot] 1
  • Implement alternative components to use WebWorker and OffscreenCanvas

    Implement alternative components to use WebWorker and OffscreenCanvas

    What problem are you trying to solve?

    In the chart.js performance documentation it mentions the possibility of using web workers to perform chart rendering in parallel with the main thread.

    Describe the solution you'd like

    Implement alternative components. Final result usage example should look like this:

    worker.js

    import 'react-chartjs-2/offscreen/worker'
    

    app.js

    import { Chart } from 'react-chartjs-2/offscreen'
    
    const worker = new Worker('worker.js')
    
    <Chart worker={worker} type='bar' data={...} /> 
    

    Source: https://github.com/reactchartjs/react-chartjs-2/issues/986

    enhancement help wanted 
    opened by dangreen 0
Releases(v5.0.1)
Owner
React components for Chart.js, the most popular charting library
null
Chart.js module for charting financial securities

Chart.js Financial Charting Chart.js module for Candlestick and OHLC charts Roadmap Chart.js 2.7.0 added our timeseries scale as new option called dis

Chart.js 620 Nov 14, 2022
Chart.js plugin to defer initial chart updates

Chart.js plugin to defer initial chart updates until the user scrolls and the canvas appears inside the viewport, and thus trigger the initial chart a

Chart.js 97 Nov 9, 2022
A Simple Dashboard Chart in Laravel Nova using Chart JS

A Simple Dashboard Chart in Laravel Nova using Chart JS. Starting create your own dashboard with Chart JS Integration can save your time and help you maintain consistency across standard elements such as Bar, Stacked, Line, Area, Doughnut and Pie Chart.

Kuncoro Wicaksono 172 Nov 18, 2022
Bar Funnel Chart extension for Chart.js

Chart.BarFunnel.js Provides a Bar Funnel Chart for use with Chart.js Documentation To create a Bar Funnel Chart, include Chart.BarFunnel.js after Char

Chart.js 58 Nov 24, 2022
TradeX-chart is a trade chart written in plain (vanilla) JavaScript with minimal dependencies

TradeX-chart is a trade chart written in plain (vanilla) JavaScript with minimal dependencies; use it with any framework or backend.

null 22 Nov 15, 2022
:bar_chart: A library of modular chart components built on D3

Plottable Plottable is a library of chart components for creating flexible, custom charts for websites. It is built on top of D3.js and provides highe

Palantir Technologies 2.9k Nov 14, 2022
Apache ECharts is a powerful, interactive charting and data visualization library for browser

Apache ECharts Apache ECharts is a free, powerful charting and visualization library offering an easy way of adding intuitive, interactive, and highly

The Apache Software Foundation 53.4k Nov 25, 2022
A reusable charting library written in d3.js

NVD3 - A reusable D3 charting library Inspired by the work of Mike Bostock's Towards Reusable Charts, and supported by a combined effort of Novus and

Novus 7.2k Nov 14, 2022
:dango: An interactive and responsive charting library

English | 简体中文 G2Plot A charting library based on the Grammar of Graphics. G2Plot is an interactive and responsive charting library. Based on the gram

AntV team 2.3k Nov 25, 2022
Ember Charts 3.5 2.3 L2 JavaScript A powerful and easy to use charting library for Ember.js

Ember Charts A charting library built with the Ember.js and d3.js frameworks. It includes time series, bar, pie, and scatter charts which are easy to

Addepar 794 Oct 22, 2022
Simple yet powerful JavaScript Charting library built using d3.js

uvCharts Simple, robust, extensible JavaScript charting library built using d3 designed to help developers embed, build charts in less than couple of

Imaginea 267 May 20, 2021
📱📈An elegant, interactive and flexible charting library for mobile.

中文 README F2 is born for mobile, developed for developers as well as designers. It is Html5 Canvas-based, and is also compatible with Node.js, Weex an

AntV team 7.8k Nov 23, 2022
Apache ECharts is a powerful, interactive charting and data visualization library for browser

Apache ECharts Apache ECharts is a free, powerful charting and visualization library offering an easy way of adding intuitive, interactive, and highly

The Apache Software Foundation 53.4k Nov 23, 2022
Open-source JavaScript charting library behind Plotly and Dash

Plotly.js is a standalone Javascript data visualization library, and it also powers the Python and R modules named plotly in those respective ecosyste

Plotly 15.2k Nov 20, 2022
Liquify charting library

Liquify Liquify: fast, multi-threaded visualization of stream data with ChartJS & Angular. The aim of Liquify is to provide a fast, customizable and e

null 4 Aug 23, 2022
📱📈An elegant, interactive and flexible charting library for mobile.

F2,一个专注于移动,开箱即用的可视化解决方案,完美支持 H5 环境同时兼容多种环境(node, 小程序,weex)。完备的图形语法理论,满足你的各种可视化需求。专业的移动设计指引为你带来最佳的移动端图表体验。英文 README 在此衷心感谢《The Grammar of Graphics》的作者

AntV team 7.8k Nov 24, 2022
An easy-to-use cross-framework JS charting library

Compact Chart Visualize your data under a minute, in any Javascript framework Table of Contents About How to use it Examples Demo Plain HTML Example w

Mireo 1 Jul 28, 2021
A server-side-rendered charting library for Fresh

fresh_charts A server side rendered charting library for Fresh based on Chart.js. Usage There are two main ways to render a chart. There is the JSX/TS

Deno 38 Nov 25, 2022
Highcharts JS, the JavaScript charting framework

Highcharts JS is a JavaScript charting library based on SVG, with fallbacks to VML and canvas for old browsers. Official website: www.highcharts.com D

Highsoft 10.9k Nov 22, 2022