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 chart.js@^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 51
  • 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 29
  • 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
  • [Bug]: Canvas is already in use. Chart with ID '0' must be destroyed before the canvas can be reused.

    [Bug]: Canvas is already in use. Chart with ID '0' must be destroyed before the canvas can be reused.

    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

    Getting this error after upgrading to new version.

    Reproduction

    hmm

    chart.js version

    3.7.1

    react-chartjs-2 version

    4.1.0

    Possible solution

    No response

    bug 
    opened by Zaid-maker 23
  • 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
  • chore(deps): update dependency jsdom to v21

    chore(deps): update dependency jsdom to v21

    Mend Renovate

    This PR contains the following updates:

    | Package | Change | Age | Adoption | Passing | Confidence | |---|---|---|---|---|---| | jsdom | ^20.0.2 -> ^21.0.0 | age | adoption | passing | confidence |


    Release Notes

    jsdom/jsdom

    v21.0.0

    Compare Source

    A potentially-breaking bug fix:

    • Fixed the window, document, location, and top properties of Window to be non-configurable. (ExE-Boss)

    Other changes:

    • Added support for <input type=image> submitting forms. (jenseng)
    • Added the location setter to the Window object, which forwards to the location.href setter. Setting the URL is still only implemented for fragment navigations, however. (ExE-Boss)
    • Fixed defer="" <script> elements that are added after DOMContentLoaded to execute, instead of being skipped.
    • Fixed selectElement.selectedOptions being incorrect when optionElement.selected is set. This was a regression introduced in v20.0.1. Unfortunately this also reverts the performance improvement when appending <option> elements that was introduced then. (eps1lon)
    • Fixed the self, locationbar, menubar, personalbar, scrollbars, statusbar, toolbar, frames, parent, external, length, and screen properties of Window to be replaceable: that is, setting them will override their values, instead of having the new value be ignored. (ExE-Boss)
    • Fixed a few issues with JSOM.fromURL() in the browser build of jsdom. (LungZeno)

    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
  • [Bug]: react-chartjs-2 is not working with React Parcel

    [Bug]: react-chartjs-2 is not working with React Parcel

    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 trying to use React ChartJs-2 in React Parcel but every time I get the error: @parcel/core: Failed to resolve 'react-chartjs-2' from './src/App.js'

    Reproduction

    https://react-chartjs-2.js.org/

    chart.js version

    v4.1.1

    react-chartjs-2 version

    v5.1.0

    Possible solution

    No response

    bug 
    opened by musmanzpak 1
  • chore(deps): update dependency @types/react-dom to v18.0.10

    chore(deps): update dependency @types/react-dom to v18.0.10

    Mend Renovate

    This PR contains the following updates:

    | Package | Change | Age | Adoption | Passing | Confidence | |---|---|---|---|---|---| | @types/react-dom (source) | 18.0.9 -> 18.0.10 | age | adoption | passing | confidence |


    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 vitest monorepo to ^0.26.0

    chore(deps): update vitest monorepo to ^0.26.0

    Mend Renovate

    This PR contains the following updates:

    | Package | Change | Age | Adoption | Passing | Confidence | |---|---|---|---|---|---| | @vitest/coverage-c8 | ^0.25.2 -> ^0.26.0 | age | adoption | passing | confidence | | vitest | ^0.25.2 -> ^0.26.0 | age | adoption | passing | confidence |


    Release Notes

    vitest-dev/vitest

    v0.26.3

    Compare Source

       🚀 Features
       🐞 Bug Fixes
        View changes on GitHub

    v0.26.2

    Compare Source

       🚀 Features
       🐞 Bug Fixes
        View changes on GitHub

    v0.26.0

    Compare Source

       🚨 Breaking Changes
       🚀 Features
       🐞 Bug Fixes
        View changes on GitHub

    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 these updates 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
  • chore(deps): update dependency eslint-config-standard-react to v13

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

    Mend Renovate

    This PR contains the following updates:

    | Package | Change | Age | Adoption | Passing | Confidence | |---|---|---|---|---|---| | eslint-config-standard-react | ^12.0.0 -> ^13.0.0 | age | adoption | passing | confidence |


    Release Notes

    standard/eslint-config-standard-react

    v13.0.0

    Compare Source

    • Update Babel instructions in Readme (#​70)
    • Add gitignore and npmrc files (#​74)
    • Add react-hooks rules (#​75)

    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
  • 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
Releases(v5.1.0)
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 630 Dec 29, 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 177 Jan 4, 2023
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
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 24 Dec 12, 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 Dec 31, 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.8k Jan 9, 2023
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 Jan 3, 2023
: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 Dec 30, 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 793 Dec 7, 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 Dec 31, 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.8k Jan 5, 2023
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.3k Jan 4, 2023
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 Dec 27, 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 57 Jan 2, 2023
Redefined chart library built with React and D3

Recharts Introduction Recharts is a Redefined chart library built with React and D3. The main purpose of this library is to help you to write charts i

recharts 19.4k Jan 2, 2023