3

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.

3
  • what do you mean by nothing is taking the curly braces away ? I didn't understand what your problem is Commented Jan 20, 2022 at 19:31
  • Do you want to mutate your array of objects? Commented Jan 20, 2022 at 19:33
  • Your question is unclear. But I notice a typo in your example code. TypeScript types and interfaces should use a semicolon ; to separate properties, not a comma ,. This is part of what helps differentiate them from object values. Example: it should be interface Option { label: string; value: string; } Commented Jan 21, 2022 at 8:51

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

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.