Aalexbit-codemod

react-stable-map-keys

Replace React .map() index-as-key with stable keys (item.id) when verifiable, otherwise add TODO

reactstandardizationa11yperformance
Public
0 executions
1 stars
How to Use
Run this codemod on your codebase using one of the following commands

The easiest way to run this codemod without installing anything globally:

Documentation

react-stable-map-keys

Replace React .map() index-as-key with stable keys (e.g. item.id) when verifiable; add TODO when not.

Problem

Using the array index as the key prop in React lists causes:

  • Reconciliation bugs: Reordering, inserting, or removing items can cause wrong component state to persist
  • Performance: React may re-render more than necessary
  • Accessibility: Screen readers can get confused by inconsistent identity

Solution

The codemod finds items.map((item, index) => <Component key={index} ... />) patterns and:

  1. Replaces with key={item.id} when we can confidently tell id exists:

    • The callback body already uses item.id (or the first param name)
    • The array is a literal like [{id: 1, name: "a"}, ...] where each element has id
  2. Adds TODO when we cannot verify: a comment above the .map() call for manual fix.

Usage

bash

Or run the transform directly:

bash

Params

ParamTypeDefaultDescription
create_branchbooleantrueCreate git branch and commit after each step
run_ai_stepbooleanfalseRun AI step for TODO-flagged cases
publish_prbooleanfalseCreate PR after push
main_branchstringmainTarget branch for PR

Metrics

  • react-stable-map-keys:
    • outcome: replaced — key was replaced with stable item.id
    • outcome: todo-added — TODO comment added, manual fix needed
    • confidence: body-uses-id | array-literal-has-id | unknown

What Gets Fixed

Automated (replaced)

  • users.map((user, i) => <div key={i}>{user.id} - {user.name}</div>)key={user.id}
  • [{id: 1, n: "a"}].map((item, idx) => <li key={idx}>{item.n}</li>)key={item.id}

Flagged (TODO)

  • items.map((item, i) => <div key={i}>{item.name}</div>) when id cannot be verified

License

MIT

Before

This is one example from the codemod's test cases. The codemod may handle many more cases.

Ready to contribute?

Build your own codemod and share it with the community.