日本語

Line and Bar Charts with Recharts in React

​​React​Playwright,Recharts,SVG,TypeScript

Recharts is a library that draws charts by combining React components. Put the axes, tooltip, legend, and lines inside <LineChart>, and you get an SVG line chart. Replace LineChart with BarChart and Line with Bar, and the same data becomes a bar chart.

The setup is short, but I ran into a few pitfalls, such as nothing being displayed unless you specify a size. This article also covers the chart size, the Y-axis ticks, and how to handle the drawing animation, with values measured in Chromium.

Note

The test environment was Ubuntu 24.04 and Node.js 22.23.4. I used recharts 3.10.1, react and react-dom 19.3.1, @types/react 19.3.0, typescript 7.0.2, and esbuild 0.28.2. I type-checked the .tsx files with tsc and then built them with esbuild. The only browser was Chromium 153 (headless), driven by Playwright 1.63.0. I did not test Firefox, Safari, real smartphones, server-side rendering with Next.js or similar, or ResponsiveContainer, which is used with older versions of Recharts.

Installing Recharts and react-is

The Recharts README says to install react-is alongside it. react-is must match the same version as the react you are using.

sh
npm install recharts react-is

In the test environment, when I installed recharts without specifying react-is, npm automatically installed react-is as a peerDependency. The installed version was 19.3.1, the same as react.

Shape the Data as One Object per X-Axis Tick

The data passed to Recharts is an array of objects. Each object corresponds to one tick on the X axis, which here is one month. You specify the values to draw as lines or bars with the object keys.

As an example, I use monthly visitor counts for web and app (fictional numbers).

ts
// data.ts
export type MonthlyVisits = {
  month: string;
  web: number;
  app: number;
};

export const visits: MonthlyVisits[] = [
  { month: '4月', web: 1200, app: 800 },
  { month: '5月', web: 1500, app: 950 },
  { month: '6月', web: 1100, app: 1300 },
  { month: '7月', web: 1800, app: 1250 },
  { month: '8月', web: 2100, app: 1600 },
  { month: '9月', web: 1900, app: 1900 },
];

Drawing a Line Chart

Pass data to LineChart and place the parts inside it.

tsx
// VisitsLineChart.tsx
import {
  CartesianGrid, Legend, Line, LineChart, Tooltip, XAxis, YAxis,
} from 'recharts';
import { visits } from './data';

export function VisitsLineChart() {
  return (
    <LineChart
      data={visits}
      responsive
      style={{ width: '100%', maxWidth: 640, aspectRatio: 1.6 }}
      margin={{ top: 16, right: 24, bottom: 0, left: 0 }}
    >
      <CartesianGrid strokeDasharray="3 3" />
      <XAxis dataKey="month" />
      <YAxis width={56} />
      <Tooltip formatter={(value) => `${Number(value).toLocaleString()}人`} />
      <Legend />
      <Line type="monotone" dataKey="web" name="Web" stroke="#00c8e8" strokeWidth={2} />
      <Line type="monotone" dataKey="app" name="アプリ" stroke="#9aa5ab" strokeWidth={2} />
    </LineChart>
  );
}

Each part has the following role:

  • CartesianGrid: the grid lines in the background
  • XAxis: the X axis. With dataKey="month", the month value of each object becomes the tick label
  • YAxis: the Y axis. The tick values are chosen automatically from the range of the values
  • Tooltip: shows that month's values when the mouse hovers over the chart
  • Legend: the legend
  • Line: the line. dataKey determines which key's values become the line

The name of Line is the name shown in the tooltip and legend. As the Line API reference describes, if you omit name, the dataKey value (web) is shown as is. The default type is linear. With type="monotone", the points are connected by curves, as in the image below.

The formatter of Tooltip is a function that rewrites the value shown in the tooltip. Here it adds commas every three digits and appends the Japanese word for people. When I hovered over the July position on the chart, the tooltip showed the July label, a Web value of 1,800 people, and a value of 1,250 people for the app series (its label is in Japanese).

Line chart with two lines. The mouse is on July, and the tooltip shows Web 1,800 people and App 1,250 people (labels in Japanese)
Line chart. Mouse placed on July

Turning the Same Data into a Bar Chart

To make a bar chart, replace LineChart with BarChart and Line with Bar. For bar colors, use fill instead of stroke on Line. Bars given fill="#00c8e8" were painted in that color. Parts such as the axes and tooltip can be used as they are.

tsx
// VisitsBarChart.tsx
import {
  Bar, BarChart, CartesianGrid, Legend, Tooltip, XAxis, YAxis,
} from 'recharts';
import { visits } from './data';

type Props = { stacked?: boolean };

export function VisitsBarChart({ stacked = false }: Props) {
  const stackId = stacked ? 'total' : undefined;
  return (
    <BarChart
      data={visits}
      responsive
      style={{ width: '100%', maxWidth: 640, aspectRatio: 1.6 }}
      margin={{ top: 16, right: 24, bottom: 0, left: 0 }}
    >
      <CartesianGrid strokeDasharray="3 3" vertical={false} />
      <XAxis dataKey="month" />
      <YAxis width={56} />
      <Tooltip formatter={(value) => `${Number(value).toLocaleString()}人`} />
      <Legend />
      <Bar dataKey="web" name="Web" fill="#00c8e8" stackId={stackId} />
      <Bar dataKey="app" name="アプリ" fill="#9aa5ab" stackId={stackId} />
    </BarChart>
  );
}

When you place two Bar components side by side, the Web and app bars line up next to each other within each month. I measured a 640px-wide chart: each bar was 35px wide, and they were placed with a 4px gap. When I hovered the mouse, a gray band (#ccc) appeared behind that month. This is the cursor drawn by Tooltip. According to the Tooltip API reference, passing cursor={false} stops it from being drawn.

Bar chart with Web and app bars side by side for each month. A gray band appears behind July (labels in Japanese)
Bar chart. Mouse placed on July

Stacking the Two Bars

Passing the same stackId to Bar stacks the bars. The Bar API reference explains that Bar components with the same axis and stackId are stacked. In the code above, the two Bar components receive 'total' only when stacked is true.

When stacked, the Y-axis scale changed to match the total. The side-by-side version ran from 0 to 2200, but the stacked version ran from 0 to 3800. This is because the total for September (1,900 + 1,900) is 3,800.

Bar chart with app bars stacked on top of Web bars for each month. The Y axis runs from 0 to 3800
Chart with stacked bars

Setting the Chart Size

A Recharts chart draws nothing unless you specify its size. The official guide on chart sizes also says so. When I rendered only <LineChart data={visits}>, the output was an empty <div class="recharts-wrapper">. No errors or warnings appeared.

There are two main ways to set the size.

The first is to specify numbers, such as width={640} height={400}. In this case, the chart is always drawn at 640×400px. When I shrank the browser width from 800px to 375px, the chart stayed at 640px. The page width became 656px, and a horizontal scrollbar appeared.

The second is to add responsive and specify the CSS size with style, as in the code in this article. width: '100%' expands the chart to the full width of the parent, maxWidth sets the upper limit on large screens, and aspectRatio keeps the width-to-height ratio. When I shrank the browser width to 375px, the chart shrank from 640×400px to 343×214px. The page width stayed at 375px.

Point

For charts that also need to be shown on smartphones, the combination of responsive and style works well.

According to the official guide, responsive was added in Recharts 3.3. In earlier versions, you can achieve a similar result by wrapping the chart in ResponsiveContainer. The guide says it is less flexible than responsive. In that case, the parent element of ResponsiveContainer must have its own size.

Setting Round Y-Axis Tick Values

With no settings, the Y-axis ticks for this data were 0, 550, 1100, 1650, and 2200. Intervals of 550 make the values hard to read.

You can set the ticks by passing the range to domain and the tick values to ticks on YAxis.

tsx
<YAxis width={56} domain={[0, 2500]} ticks={[0, 500, 1000, 1500, 2000, 2500]} />

When I changed only this line, the ticks became 0, 500, 1000, 1500, 2000, and 2500. For reference, with only domain={[0, 2500]}, the interval was 650, and with only tickCount={6}, it was 450. Neither produced round numbers. These two values were checked on a chart without an X axis.

Turning Off the Drawing Animation

When Recharts first draws a chart, it extends the lines and bars gradually. According to the API reference, the default animationDuration is 1,500 ms for Line and 400 ms for Bar.

I measured a 640×400px line chart with one line and no axes. The line is 726px long in total. At 100 ms after it appeared, about 20px was visible. At 500 ms, about 388px was visible. At 1,000 ms, about 663px was visible. At 1,700 ms, the whole line was shown.

When you do not want to wait for the drawing to finish, for example in tests that take screenshots, add isAnimationActive={false}. With this setting, the whole line was already visible at 100 ms.

tsx
<Line dataKey="web" isAnimationActive={false} />

The default for isAnimationActive is 'auto'. The API reference says that with 'auto', animation is skipped during server-side rendering, and the behavior follows whether the OS or other settings request reduced motion (prefers-reduced-motion).

I tested in Chromium with prefers-reduced-motion: reduce. Both the line chart and the bar chart without isAnimationActive had finished drawing 150 ms later. Without that setting, at 150 ms the bar height was 89px, compared with 180px when drawing was finished.

​Posted by 86