'pass an array of objects to a dropdown (select) using typescript

I'm trying to pass this array of objects

options = [
          {label:'React', value: 'react'},
          {label:'ReactNative', value: 'react-native'},
          {label:'JavaScript', value: 'js'},
          {label:'CSS', value: 'css'}        
        ];

to a select component

        <CustomSelect options={options} />

Nothing is taking the curly braces away. I've tried:

         let options: { label: string, value: string}[] = [
           {label:'React', value: 'react'},
           {label:'ReactNative', value: 'react-native'},
           {label:'JavaScript', value: 'js'},
           {label:'CSS', value: 'css'}     
         ];

this is a type array with strings in it.

I've also tried:

    interface Option {
      label: string,
      value: string
    }
    
    let options: Option[] ;
    
    options = [
      {label:'React', value: 'react'},
      {label:'ReactNative', value: 'react-native'},
      {label:'JavaScript', value: 'js'},
      {label:'CSS', value: 'css'}
    
    ];

to create an object with strings in it. My understanding is that I create an interface or a type to create an object? Once I create an object, I need to define the array of strings and I don't know how to do that correctly in a typescript way.



Solution 1:[1]

If I understand correctly from the question, you might need something like the following:

<select>
  <option value="">Select</option>
  {options.map((options) => (
    <option key={options.label} value={options.value}>
      {options.label}
    </option>
  ))}
</select>

If you want to make a custom dropdown component in typescript, this codesandbox might help

https://codesandbox.io/s/determined-rhodes-n6i8lc

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Xabir