Giter VIP home page Giter VIP logo

highcharts-react's Introduction

Highcharts React

Official minimal Highcharts wrapper for React.

Table of Contents

  1. Getting started
    1. General prerequisites
    2. Installing
    3. Using
      1. Basic usage example
      2. Highcharts with NextJS
      3. Highcharts with TypeScript
      4. Optimal way to update
  2. Options details
  3. Example with custom chart component
  4. Get repository
  5. Examples
  6. Tests
  7. Changelog
  8. FAQ
    1. Where to look for help?
    2. Why highcharts-react-official and not highcharts-react is used?
    3. How to get a chart instance?
    4. How to add a module?
    5. How to add React component to a chart's element?
    6. Why Highcharts mutates my data?

Getting Started

General prerequisites

Make sure you have node, NPM and React up to date. Tested and required versions:

  • node 8.11.3+
  • npm 6.4.1+ or similar package manager

This wrapper also requires highcharts and react packages with the following versions installed in your project:

For version 2.x.x :

  • react 16.4+
  • highcharts 5.0.0+

For version 3.x.x :

  • react 16.8+
  • highcharts 6.0.0+

Installing

Get the package from NPM in your React app:

npm install highcharts-react-official

If Highcharts is not already installed, get the package with Highcharts:

npm install highcharts highcharts-react-official

Using

Basic usage example

Import into your React project and render a chart:

import React from 'react'
import { render } from 'react-dom'
import Highcharts from 'highcharts'
import HighchartsReact from 'highcharts-react-official'

const options = {
  title: {
    text: 'My chart'
  },
  series: [{
    data: [1, 2, 3]
  }]
}

const App = () => <div>
  <HighchartsReact
    highcharts={Highcharts}
    options={options}
  />
</div>

render(<App />, document.getElementById('root'))

Highcharts with TypeScript

Live example: https://stackblitz.com/edit/react-starter-typescript-cfcznt

import React, { useRef } from 'react';
import * as Highcharts from 'highcharts';
import HighchartsReact from 'highcharts-react-official';

// The wrapper exports only a default component that at the same time is a
// namespace for the related Props interface (HighchartsReact.Props) and
// RefObject interface (HighchartsReact.RefObject). All other interfaces
// like Options come from the Highcharts module itself.

const options: Highcharts.Options = {
    title: {
        text: 'My chart'
    },
    series: [{
        type: 'line',
        data: [1, 2, 3]
    }]
};

const App = (props: HighchartsReact.Props) => {
  const chartComponentRef = useRef<HighchartsReact.RefObject>(null);

  return (
    <HighchartsReact
      highcharts={Highcharts}
      options={options}
      ref={chartComponentRef}
      {...props}
    />
  );
};
// Render your App component into the #root element of the document.
ReactDOM.render(<App />, document.getElementById('root'));

Since version 3.2.1 it is also possible to import types for props and ref independently:

import HighchartsReact, { HighchartsReactRefObject, HighchartsReactProps } from 'highcharts-react-official';

Highcharts with NextJS

Next.js executes code twice - on server-side and then client-side. First run is done in an environment that lacks window and causes Highcharts to be loaded, but not initialized. Easy fix is to place all modules inits in a if checking if Highcharts is an object or a function. It should be an object for modules initialization to work without any errors, so code like below is an easy fix:

import React from 'react'
import Highcharts from 'highcharts'
import HighchartsExporting from 'highcharts/modules/exporting'
import HighchartsReact from 'highcharts-react-official'

if (typeof Highcharts === 'object') {
    HighchartsExporting(Highcharts)
}

...

This is a know issue with NextJS and is covered here: vercel/next.js#5354

Optimal way to update

A good practice is to keep all chart options in the state. When setState is called, the options are overwritten and only the new ones are passed to the chart.update method.

Live example: https://stackblitz.com/edit/react-hketvd?file=index.js

Optimal way to update with React Hooks: https://stackblitz.com/edit/react-nwseym?file=index.js

import React, { Component } from 'react';
import { render } from 'react-dom';
import HighchartsReact from 'highcharts-react-official';
import Highcharts from 'highcharts';

class LineChart extends Component {
  constructor(props) {
    super(props);

    this.state = {
      // To avoid unnecessary update keep all options in the state.
      chartOptions: {
        xAxis: {
          categories: ['A', 'B', 'C'],
        },
        series: [
          { data: [1, 2, 3] }
        ],
        plotOptions: {
          series: {
            point: {
              events: {
                mouseOver: this.setHoverData.bind(this)
              }
            }
          }
        }
      },
      hoverData: null
    };
  }

  setHoverData = (e) => {
    // The chart is not updated because `chartOptions` has not changed.
    this.setState({ hoverData: e.target.category })
  }

  updateSeries = () => {
    // The chart is updated only with new options.
    this.setState({
      chartOptions: {
        series: [
          { data: [Math.random() * 5, 2, 1]}
        ]
      }
    });
  }

  render() {
    const { chartOptions, hoverData } = this.state;

    return (
      <div>
        <HighchartsReact
          highcharts={Highcharts}
          options={chartOptions}
        />
      <h3>Hovering over {hoverData}</h3>
      <button onClick={this.updateSeries.bind(this)}>Update Series</button>
      </div>
    )
  }
}

render(<LineChart />, document.getElementById('root'));

Options details

Available options with example values:

  <HighchartsReact
    options = { this.state.chartOptions }
    highcharts = { Highcharts }
    constructorType = { 'mapChart' }
    allowChartUpdate = { true }
    immutable = { false }
    updateArgs = { [true, true, true] }
    containerProps = {{ className: 'chartContainer' }}
    callback = { this.chartCallback }
  />
Parameter Type Required Defaults Description
options Object yes - Highcharts chart configuration object. Please refer to the Highcharts API documentation.
highcharts Object yes - Used to pass the Highcharts instance after modules are initialized. If not set the component will try to get the Highcharts from window.
constructorType String no 'chart' String for constructor method. Official constructors:
- 'chart' for Highcharts charts
- 'stockChart' for Highstock charts
- 'mapChart' for Highmaps charts
- 'ganttChart' for Gantt charts
allowChartUpdate Boolean no true This wrapper uses chart.update() method to apply new options to the chart when changing the parent component. This option allow to turn off the updating.
immutable Boolean no false Reinitialises the chart on prop update (as oppose to chart.update()) - useful in some cases but slower than a regular update.
updateArgs Array no [true, true, true] Array of update()'s function optional arguments. Parameters should be defined in the same order like in native Highcharts function: [redraw, oneToOne, animation]. Here is a more specific description of the parameters.
containerProps Object no - The props object passed to the chart container in React.createElement method. Useful for adding styles or class.
callback Function no - A callback function for the created chart. First argument for the function will hold the created chart. Default this in the function points to the chart. This option is optional.

Example with custom chart component

Create custom component ./components/MyStockChart.jsx:

import React from 'react'
import Highcharts from 'highcharts/highstock'
import HighchartsReact from 'highcharts-react-official'

const options = {
  title: {
    text: 'My stock chart'
  },
  series: [{
    data: [1, 2, 3]
  }]
}

const MyStockChart = () => <HighchartsReact
  highcharts={Highcharts}
  constructorType={'stockChart'}
  options={options}
/>

export default MyStockChart

Render your custom chart component like below:

import React from 'react'
import { render } from 'react-dom'
import MyStockChart from './components/MyStockChart.jsx'

const App = () => <div>
  <MyStockChart />
</div>

render(<App />, document.getElementById('root'))

Get repository

Clone github repository and install dependencies:

git clone https://github.com/highcharts/highcharts-react
cd highcharts-react
npm install

Examples and tests require Highcharts library, don't forget to:

npm install highcharts

Examples

There are several interesting examples in the demo folder that use all available constructors and several modules.

Bundle these with:

npm run build-demo

Demo is located under demo/index.html

Live example: https://stackblitz.com/edit/react-4ded5d?file=index.js

Tests

This wrapper contains tests for: testing environment, chart rendering and passing down container props. To run tests, type:

npm run test

Changelog

The changelog is available here.

FAQ

Where to look for help?

Technical support will help you with Highcharts and with the wrapper.

If you have a bug to report or an enhancement suggestion please submit Issues in this repository.

Why highcharts-react-official and not highcharts-react is used?

The NPM package is registered as highcharts-react-official because highcharts-react was already taken.

How to get a chart instance?

For class components and version prior to 3.0.0 use React.createRef:

constructor(props) {
  super(props)
  this.chartRef = React.createRef();
}

render() {
  return (
    <HighchartsReact
      highcharts={ Highcharts }
      options={ options }
      ref={ this.chartRef }
    />
  );
}

For functional components and version 3.0.0 and later use useRef hook:

  const chartComponent = useRef(null);
  const [options] = useState({...});

  useEffect(() => {
    const chart = chartComponent.current.chart;
    ...
  }, []);

  return <HighchartsReact ref={chartComponent} highcharts={Highcharts} options={options} />;

Alternatively store a chart reference in a callback function:

afterChartCreated = (chart) => {
  // Highcharts creates a separate chart instance during export
  if (!chart.options.chart.forExport) {
    this.internalChart = chart;
  }
}

componentDidMount() {
  // example of use
  this.internalChart.addSeries({ data: [1, 2, 3] })
}

render() {
  return (
    <div>
      <h2>Highcharts</h2>
      <HighchartsReact
        highcharts={ Highcharts }
        options={ options }
        callback={ this.afterChartCreated }
      />
    </div>
  );
}

How to add a module?

To add a module, import and initialize it:

import Highcharts from 'highcharts'
import highchartsGantt from "highcharts/modules/gantt";
import HighchartsReact from 'highcharts-react-official'

// init the module
highchartsGantt(Highcharts);

alternative with require:

import Highcharts from 'highcharts'
import HighchartsReact from 'highcharts-react-official'

require("highcharts/modules/variwide")(Highcharts);

How to add React component to a chart's element?

By using Portals it is possible to add a component to every HTML chart element.

Live example: https://codesandbox.io/s/1o5y7r31k3

Why Highcharts mutates my data?

It can be confusing, since React props are read-only, but Highcharts for performance reasons mutates the original data array. This behaviour is NOT changed by our wrapper. You need to pass a copy of your data to the wrapper if you want to prevent mutations.

Issue: #326
More discussion here: highcharts/highcharts#4259

highcharts-react's People

Contributors

anathematic avatar basts avatar benlangfeld avatar bre1470 avatar denyllon avatar dependabot[bot] avatar jon-a-nygaard avatar lucasdu4rte avatar mkruneva avatar nminhnguyen avatar ppotaczek avatar scottclayton avatar smithgraeme avatar srmelody avatar stpoa avatar tastypackets avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

highcharts-react's Issues

No animations on update

Hi...

I notice that when update the chart options, the update does not use animations. That should be improved :D

Cannot find module 'highcharts-react'

Thanks for creating this library. However, I'm getting the error, Cannot find module 'highcharts-react' after copying the sample code. I've installed all the necessary packages as well. What am I missing?

how to load completely new data and new charttype on a react highchart

I use this.setState to load new options into the highchart.
Essentially i have two scenarios:

  1. based on a few filters I want to see column chart
  2. if the filters are changed I want to see a grouped line chart

These components individually work well. However if i have loaded a highcharts react chart in grouped line chart format and I switch to the column chart for some reason the x axis still has values from the previous chart type

What is the best way to update the highchart with completely new options and data ? my problem is somehow data from a previously displayed chart type keeps showing up on the x axis even though when I console.log my chart options they are different.

My thinking is that when I change the chart options of this.state and pass it to the highcharts react compoenent it just merges the options and hence I see data from different charts

Why is this library not versioned when installed through npm ?

npm install highcharts/highcharts-react highcharts react react-dom --save
In package.json it installed the dependencies as

"highcharts": "^6.0.7",
"highcharts-react-official": "github:highcharts/highcharts-react"

why is highcharts-react-official not versioned ?

asynchronously updating options

I tried the basic example of highchart with react wrapper but couldn't update the options asynchronously.
Please check the link to code
Also , when i set a key on the root component and update the key if options are updated , then it works fine.
Is there a way to update the options directly without the need to unmount the underlying component (by changing the key).

How to use bubble charts (highcharts-more issue)

I am unable to create a chart of bubble type.

when I try:

import Highcharts from 'highcharts/highcharts-more'
<HighchartsReact
    highcharts={Highcharts}
    options={options}
/>

with chart type bubble on options I get a type error "highcharts[constructorType] is not a function"

and I get error 17 if I try:

import Highcharts from 'highcharts'
<HighchartsReact
    highcharts={Highcharts}
    options={options}
/>

What's the correct usage when highcharts-more is required? :)

How do i add annotations ?

Below is how my code looks. Everything else loads but the annotations

 var options = {
            title: {
                text: 'test'
            },
            chart: {
                type: 'column'
            },
            xAxis: {
                title: {text: 'xaxisdata'},
                categories: categories
            },

            yAxis:
                {
                    title: {
                        text: 'yaxisdata'
                    },


                },
            annotations: [{
            title: {
                 useHTML: true,
                text: '<span >drag me anywhere <br> dblclick to remove</span>',
                style: {
                    color: 'red'
                }
            },
            anchorX: "left",
            anchorY: "top",
            allowDragX: true,
            allowDragY: true,
            xValue: 515,
            yValue: 155
        }, {
            x: 100,
            y: 200,
            title: 'HELLO I AM HERE',
            anchorX: "left",
            anchorY: "top",
            allowDragY: true,
            allowDragX: false,
            shape: {
                type: 'rect',
                params: {
                    x: 0,
                    y: 0,
                    width: 55,
                    height: 40
                }
            }
        }],
            series:
                {
                    name:'hello',
                    data:  r ,

                },
            credits:{
                enabled:false
            },



        };

ALL my data loads and the chart loads but i am unable to have the annotations. How can i enable annotations?

not show the labels of axis X and Y on heat map

how can I show the labels of axis X and Y on heat map?

import React from 'react';
import Highcharts from 'highcharts';
import HC_map from 'highcharts/modules/map';
import HighchartsReact from 'highcharts-react-official';

export default class Testing extends React.Component {
  render() {
    const data1 = {
      chart: {
        type: 'heatmap',
        inverted: true
      },

      title: {
        text: 'Highcharts heat map',
        align: 'left'
      },

      subtitle: {
        text: 'Temperature variation by day and hour through May 2017',
        align: 'left'
      },

      xAxis: {
        tickPixelInterval: 50,
        min: Date.UTC(2017, 4, 1),
        max: Date.UTC(2017, 4, 5),
        type: 'datetime'
      },

      yAxis: {
        title: {
          text: null
        },
        labels: {
          format: '{value}:00'
        },
        minPadding: 0,
        maxPadding: 0,
        startOnTick: false,
        endOnTick: false,
        tickPositions: [0, 1, 2, 3, 4],
        tickWidth: 1,
        min: 0,
        max: 4
      },

      colorAxis: {
        stops: [
          [0, '#3060cf'],
          [0.5, '#fffbbc'],
          [0.9, '#c4463a']
        ],
        min: -5
      },

      series: [{
        borderWidth: 0,
        colsize: 24 * 36e5, // one day
        tooltip: {
          headerFormat: 'Temperature<br/>',
          pointFormat:  '{point.x:%e %b, %Y} {point.y}:00: <b>{point.value} ℃</b>'
        },
        data: [
          [1493596800000, 0, 1.4],
          [1493596800000, 1, 0.9],
          [1493596800000, 2, 0.3],
          [1493596800000, 3, -0.5],
          [1493596800000, 4, -0.5],
          [1493683200000, 0, 3.6],
          [1493683200000, 1, 2.6],
          [1493683200000, 2, 1.8],
          [1493683200000, 3, 1.4],
          [1493683200000, 4, 1.1],
          [1493769600000, 0, 3.8],
          [1493769600000, 1, 3.4],
          [1493769600000, 2, 2.2],
          [1493769600000, 3, 1.7],
          [1493769600000, 4, 2.1],
          [1493856000000, 0, 5.9],
          [1493856000000, 1, 4.7],
          [1493856000000, 2, 5.0],
          [1493856000000, 3, 4.7],
          [1493856000000, 4, 3.6],
          [1493942400000, 0, 6.3],
          [1493942400000, 1, 5.8],
          [1493942400000, 2, 5.3],
          [1493942400000, 3, 6.9],
          [1493942400000, 4, 6.4],
        ],
      }],
    };
    return (
       <HighchartsReact
          highcharts={Highcharts}
          constructorType={'mapChart'}
          options={data1}
        />
    );
  }
}

capture 2018-07-29 at 13 42 38 copia

with the previous code shows the heat map but without labels, using only highchart with the same configuration the labels are displayed
example: codePenExampleWithLabels

capture 2018-07-29 at 16 15 11

I think the heat map does not respect the property Xaxis and Yaxis on options.

time.useUTC is not getting configured

I have a chart options object that is configuring the time.useUTC option to false but the resulting chart is still on utc. I took the full options object and pasted on a jsfiddle and it worked there.

Indicators

I am having trouble getting indicators to work. I have imported highstock-release, but an getting an error #17 when I try to add an indicator. Here are my imports and base code:

import Highcharts from 'highcharts/highstock'
import HighstockRelease from 'highstock-release'
import HighchartsReact from 'highcharts-react-official'


....


<HighchartsReact highcharts={Highcharts}
                              constructorType={'stockChart'}
                              options={this.state.config}></HighchartsReact>

Would appreciate any help - thanks!

Importable map data

I'm trying to get maps working, specifically trying to reproduce https://jsfiddle.net/gh/get/library/pure/highslide-software/highcharts.com/tree/master/samples/mapdata/countries/au/au-all in a React project.

It seems that the map data isn't available in any official Highcharts package (eg. discussion at https://forum.highcharts.com/highmaps-usage-f14/map-not-rendering-t39804/ suggests manually importing the map you need).

Is a manual import still the only way to get the maps working? If so is there any chance the map data will get included in this or the main package in future?

tooltip.useHtml doesn't work with Highmaps

I use these options to render a map.

const options3 = {
		  title: {
		    text: ''
		  },
		  legend: {
		  	enabled: false
		  },
		  mapNavigation: {
		  	enabled: false,
		  	buttonOptions: {
		  		verticalAlign: 'top'
		  	},
		  	enableMouseWheelZoom: false
		  },

		  colorAxis: {
		  	min: Math.min.apply(Math, values),
		  	max: Math.max.apply(Math, values),
		  	minColor:'#ffffff',
		  	maxColor:'#16447e'
		  },

		  navigation: {
		  	buttonOptions: {
		  		enabled: false
		  	}
		  },

		  


		  series: [{
		  	data: array,
		  	mapData: map,
		  	joinBy: 'hc-key',
		  	states: {
		  		hover: {
		  			borderColor: '#000',
		  			brightness: 0,
		  		}
		  	},
		  	tooltip: {
		  		headerFormat: '',
		  		useHTML: true,
		  		style: {
		  			whiteSpace: 'normal'
		  		},
		  		pointFormat: '<span class="Statistics__tooltip__title">{point.title}<br/></span><span class="Statistics__tooltip__number">{point.value}</span><span class="Statistics__tooltip__text"> заявки</span>'
		  	},
		  	borderColor:'#fff'

		  }]
		};

And these styles


.highcharts-container * {
	font-family: 'Noto Sans';
}

.highcharts-tooltip-box:not([isShadow="true"]) {
	fill: #fff;
	stroke-width: 0;
	font-family: 'Noto Sans';
	padding:10px;
	box-shadow: 0 2px 10px rgba(0, 0, 0, 0.5);
	width:200px;
	border-radius: 2px;
}

.highcharts-tooltip text {
	fill: white;
	text-shadow: none;
}
.Statistics {
	&__tooltip {

		&__title {
			font-family: 'Gilroy' !important;
			font-size: 16px;
			font-weight: 800;
			font-style: normal;
			font-stretch: normal;
			line-height: 2;
			letter-spacing: normal;
			fill: #000000;
                         padding-bottom:10px;

		}

		&__number {
			font-family: 'Gilroy' !important;
			font-size: 20px;
			font-weight: 800;
			font-style: normal;
			font-stretch: normal;
			letter-spacing: 0.3px;
			fill: #005dd1;
		}

		&__text {
			font-size: 12px;
			font-weight: normal;
			font-style: normal;
			font-stretch: normal;
			line-height: normal;
			letter-spacing: normal;
			fill: #000000;
		}
	}
}

I use these options to render a map with custom style tooltip but still get tooltip in svg with tspan. Because of that some styles like padding and box-shadow do not work. What should I do?

__WEBPACK_IMPORTED_MODULE_0_highcharts___default.a.getOptions is not a function

my config/options:

import Highcharts from 'highcharts'
export default {
  xAxis: {
    type: 'datetime',
  },
  yAxis: {
    title: {
      text: 'Coin rate',
    },
  },
  plotOptions: {
    area: {
      fillColor: {
        linearGradient: {
          x1: 0,
          y1: 0,
          x2: 0,
          y2: 1,
        },
        stops: [
          [0, Highcharts.getOptions().colors[0]],
          [1, Highcharts.Color(Highcharts.getOptions().colors[0]).setOpacity(0).get('rgba')],
        ],
      },
      marker: {
        radius: 2,
      },
      lineWidth: 1,
      states: {
        hover: {
          lineWidth: 1,
        },
      },
      threshold: null,
    },
  },
  series: [{
    type: 'area',
    name: 'USD to EUR',
    data: [],
  }],
}

I get the error below,

__WEBPACK_IMPORTED_MODULE_0_highcharts___default.a.getOptions is not a function
TypeError: __WEBPACK_IMPORTED_MODULE_0_highcharts___default.a.getOptions is not a function
    at Object../lib/chartOptions.js (src/lib/chartOptions.js:30:0)
    at __webpack_require__ (webpack:/webpack/bootstrap 3227e7e02227cbe8daf1:21:0)
    at Object../components/Chart/index.js (/Users/apple/Desktop/mm/bitsector-web/.next/server/bundles/pages/coin.js:87:76)
    at __webpack_require__ (webpack:/webpack/bootstrap 3227e7e02227cbe8daf1:21:0)
    at Object../pages/coin.js (/Users/apple/Desktop/mm/bitsector-web/.next/server/bundles/pages/coin.js:666:76)
    at __webpack_require__ (webpack:/webpack/bootstrap 3227e7e02227cbe8daf1:21:0)
    at Object.3 (/Users/apple/Desktop/mm/bitsector-web/.next/server/bundles/pages/coin.js:765:18)
    at __webpack_require__ (webpack:/webpack/bootstrap 3227e7e02227cbe8daf1:21:0)
    at /Users/apple/Desktop/mm/bitsector-web/.next/server/bundles/pages/coin.js:70:18
    at Object.<anonymous> (/Users/apple/Desktop/mm/bitsector-web/.next/server/bundles/pages/coin.js:73:10)
    at Module._compile (module.js:652:30)
    at Object.Module._extensions..js (module.js:663:10)
    at Module.load (module.js:565:32)
    at tryModuleLoad (module.js:505:12)
    at Function.Module._load (module.js:497:3)
    at Module.require (module.js:596:17)

to fix it, comment, reload & uncomment the lines and then reload. But the error comes back when you reload again

          [0, Highcharts.getOptions().colors[0]],
          [1, Highcharts.Color(Highcharts.getOptions().colors[0]).setOpacity(0).get('rgba')],

I am using:

  • Create-Next-App v0.5.9
  • "next": "^6.1.1",
  • "highcharts": "^6.1.1",
  • "highcharts-react-official": "^1.4.0",
  • node v8.11.1

Potential improvement to shouldComponentUpdate.

Hello, I have received the following feedback from someone who has tested the wrapper, and I thought it best to post it here for consideration.

In my experience, the difficult part of this component is to control the chart re-rendering. So the “shouldComponentUpdate" function should be smart enough to detect any change in the options property. Us “update” property to manually refresh this component is really not a good way.

I will share this issue with the user, so you may receive further comments later, should the user want to contribute more to this case.

TypeError: Cannot assign to read only property 'exports' of object '#<Object>'

Hi team,

Getting error on line 63.

Module.
node_modules/highcharts-react-official/src/HighchartsReact.js:63
60 | return HighchartsReact;
61 | }(React.PureComponent);
62 |

63 | module.exports = HighchartsReact;
View compiled
Module../node_modules/highcharts-react-official/src/HighchartsReact.js

Please change the above highlighted line to

export default HighchartsReact;

Couldn't find preset "env" relative to drectory

When I follow the setup instructions and then launch the simulator I get the message

Failed to load bundle .... with error: (/Users/me/code/project/node_modules/highcharts-react-official/index.js: Couldn't find preset "env" relative to directory "/Users/me/code/project/node_modules/highcharts-react-office" (null))

Has anyone else seen this? Am I missing a step where I was supposed to setup an "env" variable?

WordCloud

Is there an official way to use the wordcloud type through the highcharts-react component? How can I import the wordcloud module the react way?

Would appreciate any help - thanks in advance!

ES6 imports as entry point?

Jest fails with:

highcharts-react-official/src/HighchartsReact.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import React from "react"

SyntaxError: Unexpected token import

Why won't you provide precompiled CommonJS?

HighMaps mapBubble type

Hello,
It is possible to create also HighMaps mabBubble type with series ?, because i am struggling to create that kind of map, it is possible with this library ? the map is shown but no bubble points are shown from series
I want something like this
https://www.highcharts.com/maps/demo/map-bubble
could you please provide me example of that using this library ?
thanks

Highstock chart crashes when adding any yAxis configuration

Hi,
I have this issue with highstock chart, that it crashes every time I try to add even the smallest configuration to the yAxis.

Heres an example:

 const config =  {
           yAxis: {
               title: {
                   text: 'ok'
               }
           },
           series: sensorValues
       }

And the data for this look like:

https://imgur.com/ueWMgcm

This works perfectly fine when using HighChart, not Highstock.

The error that I get (using firefox) is:

TypeError: f.options is undefined[Learn More] highstock.js:508 ./node_modules/highcharts/highstock.js/</</< highstock.js:508 ./node_modules/highcharts/highstock.js/</</a.fireEvent/< highstock.js:31 forEach self-hosted:268:13 ./node_modules/highcharts/highstock.js/</</a.each highstock.js:28 ./node_modules/highcharts/highstock.js/</</a.fireEvent highstock.js:30 setChartSize highstock.js:261 getAxisMargins highstock.js:256 getMargins highstock.js:256 redraw highstock.js:247 ./node_modules/highcharts/highstock.js/</</< highstock.js:533 ./node_modules/highcharts/highstock.js/</</a.wrap/a[n] highstock.js:20 update highstock.js:335 componentWillReceiveProps HighchartsReact.js:24 callComponentWillReceiveProps react-dom.development.js:11528 updateClassInstance react-dom.development.js:11720 updateClassComponent react-dom.development.js:13154 beginWork react-dom.development.js:13825 performUnitOfWork react-dom.development.js:15864 workLoop react-dom.development.js:15903 callCallback react-dom.development.js:100 invokeGuardedCallbackDev react-dom.development.js:138 invokeGuardedCallback react-dom.development.js:187 replayUnitOfWork react-dom.development.js:15311 renderRoot react-dom.development.js:15963 performWorkOnRoot react-dom.development.js:16561 performWork react-dom.development.js:16483 performSyncWork react-dom.development.js:16455 interactiveUpdates$1 react-dom.development.js:16720 interactiveUpdates react-dom.development.js:2150 dispatchInteractiveEvent react-dom.development.js:4533 dispatchInteractiveEvent self-hosted:1027:17

What could be causing this?

type: "arearange" gives errors/17

Happens when I dynamically add it with chart.addSeries(). I add other series in the same function, and it works fine.

					const areaRangeSeriesOption = {
						// id: tag + "Range",
						type: "arearange",
						// name: tag + "Range",
						yAxis: +index + 1,
						data: areaRangeData
						// color: colors[colorIndex],
						// step: true,
						// dataGrouping: { enabled: false }
					};

					chart.addSeries(areaRangeSeriesOption);

Updating HighStock chart when state changes

Hi!

How should we properly handle state updates when using HighStock? For example, my page loads with the data still being fetched, and when the data loading is completed, state updates and the HighStock chart will be given new options with the newly fetched data series. I am using this approach with HighCharts, and it works completely fine, how ever, when using HighStock, I get this error after state update and re render:
[Show/hide message details.] TypeError: f.options is undefined[Learn More] highstock.js:508 ./node_modules/highcharts/highstock.js/</</< highstock.js:508 ./node_modules/highcharts/highstock.js/</</a.fireEvent/< highstock.js:31 forEach self-hosted:268:13 ./node_modules/highcharts/highstock.js/</</a.each highstock.js:28 ./node_modules/highcharts/highstock.js/</</a.fireEvent highstock.js:30 setChartSize highstock.js:261 getAxisMargins highstock.js:256 getMargins highstock.js:256 redraw highstock.js:247 ./node_modules/highcharts/highstock.js/</</< highstock.js:533 ./node_modules/highcharts/highstock.js/</</a.wrap/a[n] highstock.js:20 update highstock.js:335 componentWillReceiveProps HighchartsReact.js:24 callComponentWillReceiveProps react-dom.development.js:11528 updateClassInstance react-dom.development.js:11720 updateClassComponent react-dom.development.js:13154 beginWork react-dom.development.js:13825 performUnitOfWork react-dom.development.js:15864 workLoop react-dom.development.js:15903 callCallback react-dom.development.js:100 invokeGuardedCallbackDev react-dom.development.js:138 invokeGuardedCallback react-dom.development.js:187 replayUnitOfWork react-dom.development.js:15311 renderRoot react-dom.development.js:15963 performWorkOnRoot react-dom.development.js:16561 performWork react-dom.development.js:16483 performSyncWork react-dom.development.js:16455 interactiveUpdates$1 react-dom.development.js:16720 interactiveUpdates react-dom.development.js:2150 dispatchInteractiveEvent react-dom.development.js:4533 dispatchInteractiveEvent self-hosted:1027:17

I assume that HighStock chart data updating should be handled somehow separately? Why does this approach work fine with HighChart? I have a requirement to dynamically keep adding different series to the HighStock chart, and this error is killing me :/. I have a license also if that matters.

EDIT: This also seems to have something to do with the Y axis. If I configure the Y axis to have for example a title, the chart crashes with the error above. If I DON'T define any config for the Y axis, the chart updates just fine. Weird. I also tried to access the chart instance via refs, and use .addSeries(), but the end result is the same.

Proper Changelog

Hi,

as this is the official react binding of highchart, it would be nice to have a proper changelog as ppl rely on this.

a CHANGELOG.md with proper versioning would be awesome.

When re-rendering series is null

Hi, I have tried this wrapper in my application.

I have a modal that is showing when double clicking on an item. Modal is suppose to show chart. First time it shows, but when I close modal and chart is destroyed and open modal again the series part from options is null. I store options in my state.
Part of the code:
this.state = {
options: {
title: {
text: 'My stock chart'
},
chart: {
type: 'spline',
animation: Highcharts.svg, // don't animate in old IE
marginRight: 10,
events: {
load: function () {
// set up the updating of the chart each second
var series = this.series[0];

                        temperatureIntervalId = setInterval(function () {
                            fetch('http://localhost/API/api/asset/randomNumber')
                            .then(results => {
                                return results.json();
                            }).then(data => {
                                var x = (new Date()).getTime(), // current time
                                y = data;
                                series.addPoint([x, y], true, true);
                            });
                        }, 1000);
                    }
                }
            },
            series: [{
                data: generateStartingNumbers()
            }]
        }

}

the generateStartingNumbers is a function that returns random points like in the highcharts tutorial.
The first time I open modal, everything is OK and the chart is rendering and updating after fetch adding new points to the graph.

This is how I render my modal:

render() {
return (

<HighchartsReact
ref="highchart"
highcharts={Highcharts}
constructorType={'stockChart'}
options={this.state.options}
update={true}
/>

);
}

After the second opening of the Modal from the options everything is ok except the series part which is null and I don't know why.

Thanks,
Ivan

Live Data pulling from websocket

Hello guys some body have an example where the pulling happen from websocket , i spent week trying to get it work but with no sucess here is my code

const stockOptions = {
      chart: {
         type: 'candlestick',
         animation: Highcharts.svg, // don't animate in old IE
         marginRight: 10,
         events: {
             load: function () {

                 // set up the updating of the chart each second
                 var series = this.series[0];
                 setInterval(function () {
                     var x = (new Date()).getTime(), // current time
                         y = Math.random();
                     series.addPoint([x, y], true, true);
                 }, 1000);
             }
         }
     },
     title: {
         text: 'Live random data'
     },
     xAxis: {
         type: 'datetime',
         tickPixelInterval: 150
     },
     yAxis: {
         title: {
             text: 'Value'
         },
         plotLines: [{
             value: 0,
             width: 1,
             color: '#808080'
         }]
     },

     legend: {
         enabled: false
     },
     exporting: {
         enabled: false
     },
     series: [{
         name: 'Random data',
         data: (function () {
           const socket = socketIOClient('http://localhost:3001');
                 socket.on("candle",function(data){
                    console.log(data);
                    return data
                 })
             return data;
         }())
     }]
    }


i get the data from my websocket in this format Array [ 1524387360000, 8933.5, 8933.4, 8933.5, 8933.4, 3.06687357 ] but when the chart render it empty

Can some one link me to an example with candlestick live update please ?

How to call reflow?

I have a similar problem just like this OP from StackOverflow., though obviously using this wrapper around Highcharts.

I use Highchart inside divs and the chart won't resize by itself (it only gets smaller, but never bigger) and I assume I have to call the reflow function explicitly.

So what would be the way to call reflow on the component?

How do I actually "append" a point to Highcharts.series?

I'm having a problem on the rendering speed of this.

Data comes continuously at a frequency of 100Hz or higher and I need to show them on the chart. Now I'm using a button to trigger the update process of HighchartsReact, but with the growing size of data, the update process gets quite slow and blocks UI.

After reading the code I found the update process here:

componentWillReceiveProps: function () {
this.chart.update(Object.assign({}, this.props.options), true, !(this.props.oneToOne === false))
},

It seems to update all the data every time by giving the entire "options" object to chart. I guess the chart won't diff the options. Apparently, if you draw tons of data every time, the rendering could be really slow.

In the example of Highcharts, series.addPoint is used to append data. So is there any chance I can actually "append" a point to Highcharts.series instead of writing the huge chunk of data every time?

Any other chart types available?

I really would like to use the bar chart from Highcharts in my project, as the stock chart is not really any use to me. Does this module support any other HC types of chart or just the stock chart? If so, how would I go about implementing it?

Thanks.

Bug when updating multiple series and their y_axis

Expected Behavior

When showing multiple series and their own y_axis, it should be possible to remove one series (and its y_axis).

Current Behavior

  • Adding a series and custom y_axis works fine
  • but removing one raises a Uncaught TypeError: Cannot read property 'hoverSeries' of undefined

Steps to Reproduce

This bug is reproduced in this stackblitz.
Here you have a working fork with the y_axis options commented out.

Detailed Description

This problem occurs when you need to dynamically add or remove series from a chart with their own y_axis as detailed here.

How do we change the fill color?

Hello team,

How would I go about changing the fill color, the typical options are not working such as backgroundColor, fillColor, or fillOpacity?

Please advise,
thanks!

Treemap Drilldown button disappears

Hi,
I discovered a bug when i was using the Drilldown Treemap series for my project.
So if you drilldown into the series and then you change the data ( Graph will reload) the drilldown button disappears after the graph is loaded

How to reproduce

Once you click on any of the Continents and drilldown into the series.
Then click on the 6 months radio button. The new data will be loaded
The drilldown button disappers

Live demo demonstrating bug

https://stackblitz.com/edit/react-wbxgyv

Github Repo
https://github.com/btomy/Highcharts-treemap

Versions

  • React JSX Highcharts version: 3.1.0
  • Highcharts version: 6.1.1
  • React version: 16.4.1

Trouble using sma, ema, etc indicators.

Hello, I'm trying to use the EMA indicator but am getting Error: Highcharts error #17: www.highcharts.com/errors/17 which is The requested series type does not exist.

I have added the imports

import 'highcharts/indicators/indicators';
import 'highcharts/indicators/ema';

at the top of my file and my series looks like this:

series: [{
                name: 'Candlestick',
                id: 'candles',
                type: type,
                data: initialData,
                dataGrouping: {
                    units: [
                        [
                            'day', // unit name
                            [1] // allowed multiples
                        ], [
                            'week',
                            [1]
                        ],  [
                            'month',
                            [1]
                        ]
                    ]
                },
                color: Palette.tears,
                upColor: Palette.blood,
                lineColor: Palette.iron,
            }, {
                type: 'ema',
                linkedTo: 'candles',
                params: {
                    period: 5
                }]

Obviously I am missing something here - can I get some direction please?

Support defining options as child components.

There is several who has mentioned that they would like to be able to define the chart options as children compoents.

Example:

<HighchartsReact
    highcharts={Highcharts}
    constructorType={'stockChart'}
>
    <Chart>
         <Title>My Chart Title</Title>
    </Chart>
</HighchartsReact>

I believe an easy way to support this can be that these children components is returning something that can be interpreted as an option object, and that HighchartsReact is merging this result from props.children with props.options before passing it into the constructor.

This can likely also be extended with HighchartsReact providing the said child components should this be wanted.

Difficult to use React components with Highcharts formatters.

I have received feedback from a user asking how they can render React components in a Highcharts formatter function.
This proved to be quite difficult and we should try to somehow make it more user friendly.

I made one example where I am rendering a component with a react router in xAxis.labels.formatter using a helper function named formatter: Gist
The solution was complicated by a bug in Highcharts.fireEvent, and that the Highcharts formatters expects a string in return.

One way I believe this can perhaps be simplified is that the Highcharts formatters can be modified to handle dom elements as return values.
Still this will not solve the full issue, as the Highcharts formatters will still not be able to handle a React component. So in my opinion there will likely be a need for some sort of helper as middleware.

Highcharts.charts does not remove chart properly on unmount

The Highcharts instance does not properly remove the chart from the charts array, leaving me with a
Highcharts.charts = [undefined]. And as I navigate through routing e.g history.push("/graph"), it keeps adding undefined objects once you move away from the component. So the new initialized chart will be at the end of the array.

v1.4.1 Crashes apps on React 15.

v1.4.1 Should be the major release.
Default configuration like ^1.4.0 will treat this update as minor.

ERROR in main.6050d7c9af6340703376.js from UglifyJs
SyntaxError: Unexpected token: name (React) [./~/highcharts-react-official/src/HighchartsReact.js:1,0]

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.