如何在react-select中自定义选项?

huangapple go评论76阅读模式
英文:

How to customize options in react-select?

问题

I'm using react-select but I have data in an object, not in an array, and the options only accept array values. How can I solve it?

<Select
   options={ccUsers}
   onChange={handleChange}
/>

Working data :-

const ccUsers = [
  { value: 'One', label: 'One' },
  { value: 'Two', label: 'Two' },
];

But getting data in this format :-

const ccUsers = {
    "test": "testing",
    "test": "testing"
}
英文:

I'm using react-select but I have a data in object not in array & in options only accepting array values. How can I solve it?

 &lt;Select
   options={ccUsers}
   onChange={handleChange}
 /&gt;

Working data :-

  const ccUsers = [
    { value: &#39;One&#39;, label: &#39;One&#39; },
    { value: &#39;Two&#39;, label: &#39;Two&#39; },
  ];

But getting data in this format :-

const ccUsers = {
    &quot;test&quot;: &quot;testing&quot;,
    &quot;test&quot;: &quot;testing&quot;
}

答案1

得分: 1

你可以使用 Object.entries 将其转换为数组

const obj = {
  'One': 'One',
  'Two': 'Two',
};
const ccUsers = Object.entries(obj).map(([key, value]) => ({
  label: key,
  value
}))
console.log('>>>>>>  ccUsers : ', ccUsers);
英文:

You can use Object.entries to convert into Array

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const obj = {
  &#39;One&#39;: &#39;One&#39;,
  &#39;Two&#39;: &#39;Two&#39;,
};
const ccUsers = Object.entries(obj).map(([key, value]) =&gt; ({
  label: key,
  value
}))
console.log(&#39;&gt;&gt;&gt;&gt;&gt;  ccUsers : &#39;, ccUsers);

<!-- end snippet -->

答案2

得分: 0

它接受一个类似于许多其他选择组件(例如antd Select)的{value: string, label:string}数组。您需要在将其作为属性发送之前将数据进行转换。由于您已经有一个对象中的键值对,您可以使用Object.entries()来实现这一点。链接:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries

英文:

It accepts an array of {value: string, label:string} like many other Select components, such as antd Select. You need to transform your data before sending it as a prop inside Select. Since you have key-value pairs in an object already, you can use Object.entries() to do that. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries

huangapple
  • 本文由 发表于 2023年7月20日 16:18:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/76727934.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定