0

im trying to reference a value in a list of select options, with defaultValue but i can't find a way to do it.

I'm using React and i have a Form.Select component (from react-bootstrap) where i loop through an array of objects fetched by a specific API, to dinamically render the options. In this case, im trying to set a "defaultValue" attribute, with the id of one of the items returned by the fetch.

Here's the code:

<Form.Select name="scope" onChange={(e: any)=> setLegislationModel(prevState => ({
  ...prevState, scope: e.target.value
  }))}
  defaultValue={1}
  required>
  <option value="">Select</option>
  {
    scopesList.map((item: any) => {
      return (
      <option key={item.id_scope} value={item.id_scope}>
        {item.scope_type}{item.scope_subcategory && (` (${item.scope_subcategory})`)}
      </option>
      )
    })
  }
</Form.Select>

As you can see, even if i force the defaultValue to 1, the Select still doesnt show the correct label... I think is because the value (1) in the defautltValue attribute, is not recognized by the code because the actual values are fetched on component mount and not before.

If i hard code the options, the value correctly refers to the option.

A sample of object in the list of options is:

[
  {
     id_scope: 1, //1 to 4
     scope_type: "a string",
     scope_subcategory: "another string"
  }
]

Is there a way to set the defaultValue to a number like 1, 2, 3 or 4 and so reference to the option with that value in the select? So i can show that value's label?

Thank you for your help

simpet24
  • 33
  • 6
  • 1
    I personally would create a external function that builds the list out and stores it in a constant (let's call it `optionsList`), and THEN sets a hook with the value you want set .. outside the function, set your initial hook: `const [hook, setYourHook] = React.useState(1);` Inside that function, you would `setYourHook(whatever)` AFTER the loop ran to create the list object. Then you would just have `defaultValue={hook}` and inside your ` – Zak Jun 14 '23 at 17:04

0 Answers0