1
\$\begingroup\$

While trying to integrate react-select component on my codebase on documentation it's explained that you can pass an array of options with label and value attributes eg :

import Select from 'react-select';
let options = [
 {
 label: 'Color',
 value: 'Blue'
 }
]
<Select options={options} />

And it works fine, but in my case I need value to be an object as simply a String won't do the job how I want. I know I can keep an array of objects separately and do a find based on their ID on that array but this lacks on performance and increases chances for side effects.

So what I tried was using options with value as objects :

let options = [
 {
 label: 'Color',
 value: {
 r: 123,
 g: 78,
 b: 198
 }
 }
]

But this way I had errors on my console, telling me that you have to use unique keys for each child and this was because the component takes an option value and uses that for key and that key when converted to string became "[object Object]" so finally the key was always option-[object Object] .

To solve this out I overrode the value attribute toString() method and it worked :

let options = [
 {
 label: 'Color',
 value: {
 r: 123,
 g: 78,
 b: 198,
 toString: function(){
 return this.r + this.g + this.b;
 }
 }
 }
]

So what could be downsides of this, as obviously this is a hack.

mdfst13
22.4k6 gold badges34 silver badges70 bronze badges
asked Apr 13, 2016 at 16:29
\$\endgroup\$
1
  • \$\begingroup\$ Not your typical CR question, but I'm intrigued by the format of it. ++ Welcome to Code Review. \$\endgroup\$ Commented Apr 14, 2016 at 0:59

1 Answer 1

1
\$\begingroup\$

One possible down-site of this could be a performance issue and this depends on how toString() is implemented.

On my case I did it like this :

let options = [
 {
 label: 'Color',
 value: {
 r: 123,
 g: 78,
 b: 198,
 toString: function(){
 return uuid.v1();
 }
 }
 }
]

Whenever the state or props are updated React uses a diff. algorithm to check if it's VirtualDOM and DOM corresponds, which means every time React looped through options they had a different key value and React re-rendered every option no matter if their value changed or not.

In my case a fix was to hash the value object using this library;

let options = [
 {
 label: 'Color',
 value: {
 r: 123,
 g: 78,
 b: 198,
 toString: function(){
 return hash(this);
 }
 }
 }
]
answered Apr 14, 2016 at 7:47
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.