Skip to content

missing key in the demonstration code #4

Description

@Pomax

The demonstration code of https://d4.js.org shows the following example code:

const paths = voronoi(samples)
    .polygons()
    .map(sample => (
      <path
        d={`M${sample.join('L')}Z`}
        fill={color(sample.data)}
        stroke={color(sample.data)}
      />
    ));

but this is missing a key for React to do efficient DOM diffing. Without it you'll get both console warnings, and potentially slow operations where two samples being swapped causes React to instead rebuild them instead of just swapping them.

For properly taking advantage of React, you'll want something like this:

const paths = voronoi(samples)
    .polygons()
    .map(sample => (
      <path
        key={sample.id}
        d={`M${sample.join('L')}Z`}
        fill={color(sample.data)}
        stroke={color(sample.data)}
      />
    ));

where sample.id is a unique identifier for a sample.

And note that, while tempting, you can't use map( (sample,idx) => ....key={idx} ) because the sample's position in the list is not uniquely identifying for the sample (that's only unique information for the specific list the samples are currently in), so successive calls with a reordered array would still make React perform far worse than if a proper unique value is used as key.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions