Skip to content

RThong/use-react-echarts

Repository files navigation

use-react-echarts

React hooks for Apache Echarts.

License ECharts Ver React Ver

Install

$ pnpm add use-react-echarts -S

# `echarts` is the peerDependence of `use-react-echarts`, you can install echarts with your own version.
$ pnpm add echarts -S

Usage

1. Basic usage

import useReactEcharts from 'use-react-echarts';

// This will import all the charts and components in ECharts
const [ref, chart] = useReactEcharts({ options })

// Only import required charts and components 
const [ref, chart] = useReactEcharts({ echarts, ...option })
  • option The echarts option config.

  • echarts For minimal bundle of echarts. By default, use-react-echarts import all the charts and components in ECharts.You can pass the echarts props with the required Echarts modules to reduce bundle size

2. Import ECharts modules manually to reduce bundle size

import type { BarSeriesOption, LineSeriesOption } from 'echarts/charts'
import { BarChart, LineChart } from 'echarts/charts'
import type {
  DatasetComponentOption,
  GridComponentOption,
  TitleComponentOption,
  TooltipComponentOption
} from 'echarts/components'
import {
  DataZoomComponent,
  GridComponent,
  LegendComponent,
  TitleComponent,
  ToolboxComponent,
  TooltipComponent,
  VisualMapComponent
} from 'echarts/components'
import * as echarts from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { useEffect } from 'react'

import useReactEcharts from 'use-react-echarts'

// Register the required components
echarts.use([
  CanvasRenderer,
  TooltipComponent,
  GridComponent,
  BarChart,
  DataZoomComponent,
  LineChart,
  ToolboxComponent,
  TitleComponent,
  LegendComponent,
  VisualMapComponent
])

type ECOption = echarts.ComposeOption<
  | BarSeriesOption
  | LineSeriesOption
  | TitleComponentOption
  | TooltipComponentOption
  | GridComponentOption
  | DatasetComponentOption
>

const App = () => {
  const [ref, chart] = useReactEcharts({ echarts, options})

  return <div ref={ref} style={{ height: 380 }} />
}

Please read import-echarts for more details.

Result

  • ref Echarts instance container, usually is a element.

  • chart The echarts instance object, then you can use any API of echarts. For example:

const [ref, chart] = useReactEcharts({ options })

useEffect(() => {
  if(!chart) return
  chart.setOption(option)
}, [chart])

return <div ref={ref} style={{ height: 380 }} >

About API of echarts, can see https://echarts.apache.org/api.html#echartsInstance.

LICENSE

MIT@Hong.

About

React hooks for ECharts

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published