Charts in React
Move the dashboard into a React app: D3 for the maths, React for the marks, refs for axes and zoom, and Recharts, visx, Chart.js and ECharts compared.
Most company front ends are React apps, so sooner or later a chart has to live inside one. The hard part is not drawing: it is that React and D3 both want to own the page. This phase gives you one clear rule for who owns what, and shows the few places where the rule bends: axes, zoom and canvas.
You build the same charts three ways: D3 for the maths with React drawing every mark, D3 writing into a ref that React leaves alone, and a ready-made library (Recharts). Then you meet visx, Chart.js, ECharts and Observable Plot, see what each one costs in size and in lines of code, and type a chart component with TypeScript.
At the end the Lumen dashboard runs as a React app: the rides line is D3 maths with JSX marks, the stations chart is Recharts, and every box has its own loading, error and empty state.
Phase 14 · the story
Arjun, engineer
“The company's main app is in React, and I have to move the dashboard into it without rewriting every chart from scratch.”
Lumen Bikes' rider app and its back-office pages are written in React. The dashboard so far is plain JavaScript that draws into boxes by id. On Tuesday the product manager asks Arjun to put it inside the back office, with the same login, the same menu and the same state as every other page.
Arjun tries the obvious thing: he calls his chart functions from a React component. The first draw works. The second draw, after a month change, doubles the axes. In development, React runs every effect twice and he sees two charts stacked on one canvas. A copy-pasted Recharts example draws nothing at all.
None of this is a bug in D3 or React. Each one has an owner for the page, and they have not agreed who. In this phase you agree it for them, move the rides line and the stations chart across, and keep the loading, error and empty states the dashboard already had.
In this phase
You will learn
- Decide, for any chart, whether D3 or React owns each DOM node, and write the chart without the two fighting
- Put D3 axes, zoom and canvas drawing into a ref and an effect with a proper cleanup, and explain StrictMode's double effect
- Use Recharts, and tell when visx, Chart.js, ECharts or Observable Plot fits better
- Run the Lumen dashboard as a React app in your Vite project
You write code in
In your Vite project lumen-dashboard/, now with React (run npm run dev), and in the editor on this page
Files you touch
- vite.config.js
- package.json
- index.html
- src/main.jsx
- src/App.jsx
- src/charts/RidesLine.jsx
- src/charts/StationsBar.jsx
Practise this phase
Hands-on exercises: write the code, see your page live, and press Check to have it tested automatically.