liveBook · Manning

React key

As explained in D3.js in Action, Third Edition

A React key prop identifies an item in a component collection so React can track changes between renders.

A React key gives each item in a rendered collection a stable identity, helping React track which DOM item to update when data changes. section 8.6.1

Keys in a scatterplot

Map over framework data and give every Circle a unique key, such as key={`circle-${framework.id}`}. Keep the key tied to the item’s identifier while scales calculate its position and color. section 8.6.1

Use keys when rendering repeated components:

Listing 8.10 Appending circles (ScatterplotReactControlled.js)
...
import * as d3 from 'd3';                                     #1
import Circle from '../ChartComponents/Circle';              

const ScatterplotReactControlled = props => {
  ...

  const xScale = d3.scaleLinear()                            #2
    .domain([0, d3.max(props.data, d => d.user_count)])     
    .range([0, innerWidth])                                  
    .nice();                                                
  const yScale = d3.scaleLinear()                           
    .domain([0, 100])                                        
    .range([innerHeight, 0]);                               

  return (
    <Card>
      <h2>Retention vs Usage</h2>
      <ChartContainer ... >
        {props.data.map(framework => (         
          <Circle                                             
            key={`circle-${framework.id}`}         #3
            cx={xScale(framework.user_count)}  
            cy={yScale(framework.retention_percentage)}      
            r={6}                              
            fill={props.colorScale(framework.id)}      
          />                              
        ))}                             
      </ChartContainer>
    </Card>
  )
};

export default ScatterplotReactControlled;

Inspect the complete scatterplot mapping, including the key assigned to each Circle. section 8.6.1

How D3.js in Action, Third Edition covers it

How deep it goes
Demonstrates unique keys in mapped circles and axis ticks, without detailing React’s reconciliation internals.
Examples
Uses framework circles keyed with circle-${framework.id} and axis tick groups keyed with tick values.
What it assumes
Assumes familiarity with React components, props, JavaScript map, and basic SVG chart rendering.
What you can do after
Build repeated React visualization elements with unique keys and map data into trackable components.
How it connects
Connects keys to React components, JavaScript map, DOM updates, D3 scales, SVG circles, and axis ticks.

Also explained in

Compare how 3 books explain React key →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of D3.js in Action, Third Edition. The section links point to the parts of the book it draws on.