D3 Core: Selections and the Data Join
Learn D3's one big idea: bind an array to elements with the data join, so a chart redraws correctly when the data changes: enter, update, exit and keys.
Until now you drew every bar in a loop, and when the data changed you had to wipe the chart and start again. This phase gives you D3's answer: selections (a list of page elements you can change together) and the data join (a rule that pairs each item of an array with one element).
You meet the join on plain divs first, where you can see every step, then on SVG bars. You learn why a key keeps the right bar attached to the right station, what goes wrong without one, and how to react to clicks and pointer moves without piling up listeners.
At the end the dashboard gets its first chart that updates: the busiest stations, with a month selector. Switching month adds, moves and removes bars, and nothing is redrawn from scratch.
Phase 5 · the story
Arjun, engineer
“Every time the data changes, my hand-made chart draws a second copy on top of the first or loses its bars, and I do not trust it.”
Arjun wrote the rides chart by hand in Phase 3. It works, once. Then Priya asks to look at May instead of July, and his code appends 25 new bars under the 25 it already drew. He fixes that by clearing the whole chart before every draw. Now the page flickers, a bar being hovered loses its tooltip, and a station that moved up one rank jumps instead of sliding.
He has read that D3 solves exactly this with something called the data join, and that most chart bugs in D3 are join bugs. He wants to understand it properly before the dashboard grows ten more charts that all depend on it.
In this phase you learn the join from the bottom up. By the end the team's station chart updates in place: bars that stay are kept, new stations appear, stations without rides disappear, and you can explain why.
In this phase
You will learn
- Select page elements with D3 and change them, and say what an empty selection does
- Explain the data join: which items enter, which update and which exit, and why you add a key
- Draw SVG bars from an array that redraw correctly when the array changes
- Attach click and pointer handlers to chart marks without double-binding them
You write code in
In your Vite project lumen-dashboard/ (run npm run dev), and in the editor on this page
Files you touch
- src/charts/stations-bar.js
- src/data/load.js
- src/main.js
- index.html
Practise this phase
Hands-on exercises: write the code, see your page live, and press Check to have it tested automatically.