Skip to content

Setting Picker Item key prop causes keys to be coerced to a string regardless of the actual type #6103

Open
@bmingles

Description

@bmingles

Provide a general summary of the issue here

The Picker component supports items with numeric id / key props.

Item.key unset

If the Item.key prop is not explicitly set, keys get derived from the id or key props on the items array.

e.g.

function Example() {
  let items = [
    { id: 1, name: 'Aardvark' },
    { id: 2, name: 'Cat' },
    { id: 3, name: 'Dog' },  ];
    
  let [animalId, setAnimalId] = React.useState(null);

  return (
    <>
      <Picker
        label="Pick an animal"
        items={items}
        onSelectionChange={setAnimalId}
        value={animalId}
      >
        { /* Item.key not explicitly set */
          (item) => <Item>{item.name}</Item>
        }
      </Picker>
      <p>Animal id type: {typeof animalId}</p>
    </>
  );
}

The onSelectionChange handler will pass a numeric key to setAnimalId (consistent with the items data) and value + defaultValue will work with values of type number.

Item.key explicitly set

If the Item.key prop is explicitly set e.g.

<Item key={item.id}>{item.name}</Item>}

The onSelectionChange will pass a string id to setAnimalId, and the value + defaultValue props will require values of type string in order to work.

🤔 Expected Behavior?

I would expect in the case of setting Item.key prop explicitly:

  • onSelectionChange should pass the actual value (not the stringified version) of the original id / key
  • value, and defaultValue should be able to match the id / key prop on the items instead of requiring them to be string values

😯 Current Behavior

When Item.key prop is explicitly set

  • onSelectionChange passes a stringified value of the original id / key
  • value, and defaultValue don't match the items id / key prop unless they are stringified

💁 Possible Solution

No response

🔦 Context

We have a wrapper component that needs to explicitly set the Item.key prop based on properties on the items. In cases where these props are numeric or boolean types, this forces the input value + onSelectedValue change handlers to work with strings which doesn't match the original data.

🖥️ Steps to Reproduce

https://codesandbox.io/p/sandbox/modern-shadow-znqpwf

Version

3.34.1

What browsers are you seeing the problem on?

Chrome

If other, please specify.

No response

What operating system are you using?

MacOS

🧢 Your Company/Team

No response

🕷 Tracking Issue

No response

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions