2

How can I add key element to react-select with ismulti, so when I select multiple options it doesn't give me this error "Warning: Encountered two children with the same key, [object Object]. Keys should be unique so that components maintain their identity across updates. Non-unique keys may cause children to be duplicated and/or omitted — the behavior is unsupported and could change in a future version."

here is my code:

         let options = data.map( (item,index) => (
             { index: item.name, value: item, label: item.name })
             );
   
      setOptions(options);

in the return part here is how I'm setting the react-select

 <Select 
        
            value={selectedOptions || ''}       
            className="select-name"
            isMulti
            name="selectedOption"
            onChange={handleChange}
            isClearable             
            options={Options}              
        />

Thanks in advance for your help.

2 Answers 2

2

There's a solution suggested on the discussion about the same issue on github.

Essentially you would add a toString method to the object used as the value in your options. This allows you to control the format of the key (which otherwise is generated by casting the value property to a string, hence the duplicated [object Object] keys.

In your case it might look something like this:

const options = data.map((item, index) => ({
  index: item.name,
  value: {
    ...item,
    toString: () => item.id // assumes item has a unique id property
  },
  label: item.name
}));

setOptions(options);
Sign up to request clarification or add additional context in comments.

Comments

1

You can use the getOptionValue prop from the Select component like so:

getOptionValue={({ value }) => value.name}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.