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.

\$\endgroup\$
  • \$\begingroup\$ Not your typical CR question, but I'm intrigued by the format of it. ++ Welcome to Code Review. \$\endgroup\$ – RubberDuck Apr 14 '16 at 0:59
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);
      }
    }
  }
]
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.