7 React Chart Libraries for Your Web Projects

7 React Chart Libraries For Your Web Projects

Web developers usually have a very deep relationship with graphs and charts. While working on a project we have to somehow retrieve data from the database and display it in a meaningful way.

Most of the time, you see the beautiful graphs in the admin dashboard of an application. Honestly, admins and website owners really need to see the visuals (big picture) of how their app is performing.

Today, I’ve compiled a list of best open source React chart libraries that you can easily integrate into your web projects. I have also provided a bar chart example for each library so that you can quickly compare them to select the best one for your project.

The major benefit of using an existing data visualization library is that you don’t have to re-invent the wheel. Meaning that you can focus on producing the actual data and leave the heavy-lifting of designing the graphs and charts on the library itself.

So, without any further ado let’s have a look at charting libraries for React.


Recharts

Recharts Homepage

Recharts Homepage

Recharts has no match when it comes to the community size and the number of contributors that are actively maintaining this cool library. It is a data visualization library that combines the power of React and D3.js .

It is specifically designed to help you add graphs and charts in your React-based web applications.

The major plus point of Recharts is that it fully supports the SVG (Scalable Vector Graphics). It means that you will get pixel perfect graphs with a very small footprint.

Simple Bar Chart Example Code:

import React, { PureComponent } from 'react';
import {
  BarChart, Bar, Cell, XAxis, YAxis, CartesianGrid, Tooltip, Legend,
} from 'recharts';

const data = [
  {
    name: 'Page A', uv: 4000, pv: 2400, amt: 2400,
  },
  {
    name: 'Page B', uv: 3000, pv: 1398, amt: 2210,
  },
  {
    name: 'Page C', uv: 2000, pv: 9800, amt: 2290,
  },
  {
    name: 'Page D', uv: 2780, pv: 3908, amt: 2000,
  },
  {
    name: 'Page E', uv: 1890, pv: 4800, amt: 2181,
  },
  {
    name: 'Page F', uv: 2390, pv: 3800, amt: 2500,
  },
  {
    name: 'Page G', uv: 3490, pv: 4300, amt: 2100,
  },
];

export default class Example extends PureComponent {
  static jsfiddleUrl = 'https://jsfiddle.net/alidingling/30763kr7/';

  render() {
    return (
      <BarChart
        width={500}
        height={300}
        data={data}
        margin={{
          top: 5, right: 30, left: 20, bottom: 5,
        }}
      >
        <CartesianGrid strokeDasharray="3 3" />
        <XAxis dataKey="name" />
        <YAxis />
        <Tooltip />
        <Legend />
        <Bar dataKey="pv" fill="#8884d8" />
        <Bar dataKey="uv" fill="#82ca9d" />
      </BarChart>
    );
  }
}

Victory

Victory Homepage

Victory Homepage

Victory is packed with React components that can help us integrate high-quality charts on websites. It is powered by the team of designers and developers from a renowned software development company Formidable .

It is flexible enough to generate a line, bar, pie, and even candlestick charts.

A cool thing that I noticed about Victory is that it offers an identical API through which you can easily generate charts for Android and iOS platforms.

Bar Chart Example Code Snippet:

<VictoryChart
  theme={VictoryTheme.material}
  domainPadding={10}
>
  <VictoryBar
    style={{ data: { fill: "#c43a31" } }}
    data={sampleData}
  />
</VictoryChart>

Vx

VX Homepage

VX Homepage

vx has many things in common with the Recharts library. It uses D3 to perform mathematical computations while React enables it to update the DOM. You can use vx to generate flexible data visualizations for admin panels.

It is well equipped to generate complex charts like patterns, chord, dendrograms, treemap, and Voronoi diagram.

Code for a simple bar chart:

import React, { useMemo } from 'react';
import { Bar } from '@vx/shape';
import { Group } from '@vx/group';
import { GradientTealBlue } from '@vx/gradient';
import letterFrequency, { LetterFrequency } from '@vx/mock-data/lib/mocks/letterFrequency';
import { scaleBand, scaleLinear } from '@vx/scale';

const data = letterFrequency.slice(5);
const verticalMargin = 120;

// accessors
const getLetter = (d: LetterFrequency) => d.letter;
const getLetterFrequency = (d: LetterFrequency) => Number(d.frequency) * 100;

export type BarsProps = {
  width: number;
  height: number;
  events?: boolean;
};

export default function Example({ width, height, events = false }: BarsProps) {
  // bounds
  const xMax = width;
  const yMax = height - verticalMargin;

  // scales, memoize for performance
  const xScale = useMemo(
    () =>
      scaleBand<string>({
        rangeRound: [0, xMax],
        domain: data.map(getLetter),
        padding: 0.4,
      }),
    [xMax],
  );
  const yScale = useMemo(
    () =>
      scaleLinear<number>({
        rangeRound: [yMax, 0],
        domain: [0, Math.max(...data.map(getLetterFrequency))],
      }),
    [yMax],
  );

  return width < 10 ? null : (
    <svg width={width} height={height}>
      <GradientTealBlue id="teal" />
      <rect width={width} height={height} fill="url(#teal)" rx={14} />
      <Group top={verticalMargin / 2}>
        {data.map(d => {
          const letter = getLetter(d);
          const barWidth = xScale.bandwidth();
          const barHeight = yMax - yScale(getLetterFrequency(d));
          const barX = xScale(letter);
          const barY = yMax - barHeight;
          return (
            <Bar
              key={`bar-${letter}`}
              x={barX}
              y={barY}
              width={barWidth}
              height={barHeight}
              fill="rgba(23, 233, 217, .5)"
              onClick={() => {
                if (events) alert(`clicked: ${JSON.stringify(Object.values(d))}`);
              }}
            />
          );
        })}
      </Group>
    </svg>
  );
}

Nivo

Nivo Homepage

Nivo Homepage

Unlike other data visualization libraries, nivo provides us the ability to generate charts on the server-side.

Here’s a brief guide about how it works on the server-side.

Basically, we have to send a POST request on the server with the available data. nivo then creates a chart and return its URL in response. The endpoint of the POST request must be able to process the chart data. Finally, you can customize the returned URL however you like.

You can add transition effects and animations in charts to make them more engaging. This feature will definitely help you enhance the user experience.

nivo is capable of generating responsive charts using pure HTML, SVG, and canvas. You can also add gradients in charts with a few lines of code. But, remember that gradients are not supported for charts that are created using canvas.

Bar chart example using SVG:

import { ResponsiveBar } from '@nivo/bar'
// make sure parent container have a defined height when using
// responsive component, otherwise height will be 0 and
// no chart will be rendered.
const MyResponsiveBar = ({ data /* YOUR DATA HERE */ }) => (
    <ResponsiveBar
        data={data}
        keys={[ 'hot dog', 'burger', 'sandwich', 'kebab', 'fries', 'donut' ]}
        indexBy="country"
        margin={{ top: 50, right: 130, bottom: 50, left: 60 }}
        padding={0.3}
        colors={{ scheme: 'nivo' }}
        defs={[
            {
                id: 'dots',
                type: 'patternDots',
                background: 'inherit',
                color: '#38bcb2',
                size: 4,
                padding: 1,
                stagger: true
            },
            {
                id: 'lines',
                type: 'patternLines',
                background: 'inherit',
                color: '#eed312',
                rotation: -45,
                lineWidth: 6,
                spacing: 10
            }
        ]}
        fill={[
            {
                match: {
                    id: 'fries'
                },
                id: 'dots'
            },
            {
                match: {
                    id: 'sandwich'
                },
                id: 'lines'
            }
        ]}
        borderColor={{ from: 'color', modifiers: [ [ 'darker', 1.6 ] ] }}
        axisTop={null}
        axisRight={null}
        axisBottom={{
            tickSize: 5,
            tickPadding: 5,
            tickRotation: 0,
            legend: 'country',
            legendPosition: 'middle',
            legendOffset: 32
        }}
        axisLeft={{
            tickSize: 5,
            tickPadding: 5,
            tickRotation: 0,
            legend: 'food',
            legendPosition: 'middle',
            legendOffset: -40
        }}
        labelSkipWidth={12}
        labelSkipHeight={12}
        labelTextColor={{ from: 'color', modifiers: [ [ 'darker', 1.6 ] ] }}
        legends={[
            {
                dataFrom: 'keys',
                anchor: 'bottom-right',
                direction: 'column',
                justify: false,
                translateX: 120,
                translateY: 0,
                itemsSpacing: 2,
                itemWidth: 100,
                itemHeight: 20,
                itemDirection: 'left-to-right',
                itemOpacity: 0.85,
                symbolSize: 20,
                effects: [
                    {
                        on: 'hover',
                        style: {
                            itemOpacity: 1
                        }
                    }
                ]
            }
        ]}
        animate={true}
        motionStiffness={90}
        motionDamping={15}
    />
)

React-Vis

React-Vis Homepage

React-Vis Homepage

react-vis is a library created by Uber Open Source developers. It consists of reusable React components for generating different kinds of charts. For example, you can display data as heat maps, donut charts, radar charts, Sankey diagrams, and many other common data visualization formats.

Bar Chart Example:

import React from 'react';
import ShowcaseButton from '../showcase-components/showcase-button';
import {
  XYPlot,
  XAxis,
  YAxis,
  VerticalGridLines,
  HorizontalGridLines,
  VerticalBarSeries,
  VerticalBarSeriesCanvas,
  LabelSeries
} from 'index';

const greenData = [{x: 'A', y: 10}, {x: 'B', y: 5}, {x: 'C', y: 15}];

const blueData = [{x: 'A', y: 12}, {x: 'B', y: 2}, {x: 'C', y: 11}];

const labelData = greenData.map((d, idx) => ({
  x: d.x,
  y: Math.max(greenData[idx].y, blueData[idx].y)
}));

export default class Example extends React.Component {
  state = {
    useCanvas: false
  };

  render() {
    const {useCanvas} = this.state;
    const content = useCanvas ? 'TOGGLE TO SVG' : 'TOGGLE TO CANVAS';
    const BarSeries = useCanvas ? VerticalBarSeriesCanvas : VerticalBarSeries;
    return (
      <div>
        <ShowcaseButton
          onClick={() => this.setState({useCanvas: !useCanvas})}
          buttonContent={content}
        />
        <XYPlot xType="ordinal" width={300} height={300} xDistance={100}>
          <VerticalGridLines />
          <HorizontalGridLines />
          <XAxis />
          <YAxis />
          <BarSeries className="vertical-bar-series-example" data={greenData} />
          <BarSeries data={blueData} />
          <LabelSeries data={labelData} getLabel={d => d.x} />
        </XYPlot>
      </div>
    );
  }
}

BizCharts

BizCharts Homepage

BizCharts Homepage

BizCharts is a data visualization library developed by the tech giant Alibaba. It has the biggest collection of chart designs which makes it the ideal choice for almost every use case.

I would recommend BizCharts for beginners who never used any charting library before. The reason is simple, BizCharts has a very minimalistic code that encourages newbies to get started as quickly as possible.

Bar Chart Example:

import { Chart, Interval, Tooltip } from 'bizcharts';

const data = [
  { year: '1951 年', sales: 38 },
  { year: '1952 年', sales: 52 },
  { year: '1956 年', sales: 61 },
  { year: '1957 年', sales: 45 },
  { year: '1958 年', sales: 48 },
  { year: '1959 年', sales: 38 },
  { year: '1960 年', sales: 38 },
  { year: '1962 年', sales: 38 },
];


function Demo() {
  return <Chart height={400} autoFit data={data} interactions={['active-region']} padding={[30, 30, 30, 50]} >
    <Interval position="year*sales" />
    <Tooltip shared />
  </Chart>
}

ReactDOM.render(<Demo />, mountNode);

React-Chartjs-2

React ChartJS 2 Homepage

React ChartJS 2 Homepage

Did you hear about the popular JavaScript charting library Chart.js ?

react-chartjs-2 is like a wrapper around that library so that it can work seamlessly in React apps. Basically, it gives you all the features of the Chart.js library which you can access using React props and components.

Bar Chart Example:

import React from 'react';
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 React.createClass({
  displayName: 'BarExample',

  render() {
    return (
      <div>
        <h2>Bar Example (custom size)</h2>
        <Bar
          data={data}
          width={100}
          height={50}
          options={{
            maintainAspectRatio: false
          }}
        />
      </div>
    );
  }
});

Conclusion

These days, data plays a key role in determining the success or failure of a business. As a React developer, we should equip our selves with data visualization libraries to help web owners see the performance reports in an efficient way.

The react chart libraries I mentioned above will help you create a significant impact on how businesses analyze the data.

If you read my articles often you probably know that I love React. I’ve created some similar articles before that I think can be very interesting if you liked this one. Check them out here:

Best Productivity Tools for React Developers

7 Awesome React Hoos

Thanks for reading!

If you liked what you saw, please support my work!

Juan Cruz Martinez - Author @ Live Code Stream

Juan Cruz Martinez

Juan has made it his mission to help aspiring developers unlock their full potential. With over two decades of hands-on programming experience, he understands the challenges and rewards of learning to code. By providing accessible and engaging educational content, Juan has cultivated a community of learners who share their passion for coding. Leveraging his expertise and empathetic teaching approach, Juan has successfully guided countless students on their journey to becoming skilled developers, transforming lives through the power of technology.