Search code examples
javascripthtmlreactjsreactstrap

How to set the default value of a select option when mapping over array


I am using CustomInput from reactstrap. I am setting the type to select. In my CustomInput type="select" I am mapping over options from an array. I need to set the default value in the select to an particular option that is being mapped over. eg. Id like the default to be united states or germany, right now I am mapping over an array of different countries.

Here is my code below

<CustomInput
          type="select"
          id="country"
          name="country"
          className="mb-3"
          value={country.countryCode}
          onChange={handleChange}
        >
          
          {numberCountries.map(({countryCode, name}) => ( 
            <Fragment>
              <option key={countryCode} value={countryCode}>{name}</option> <--- how can i set a one of these options to be the default value rendered on the screen?
            </Fragment>
          ))}
       
        </CustomInput>

Here is the object I am mapping over

[
{
    name: 'United States',
    countryCode: 'US'
  },
{
    name: 'Germany',
    countryCode: 'DE'
  }
]

Solution

  • DOM might support a default value, but in a controlled input component, you have to come up with

      <input value={value} onChange={onChange} />
    

    And the value has to be the current value you selected. so if you ever change it based on the use selection, you have to set it via.

      const onChange = e => {
        setValue(e.target.value)
      }
    

    Which means the value is ALWAYS in sync with selection. This is different if you work with DOM directly.

    Ok, now with this understanding, if you want to set some default stuff, you can do.

      const [value, setValue] = useState(country.countryCode || defaultCode)
    

    To be honest, even DOM offers a default behavior, you should want to override it. Because otherwise you'll end up with some bizarre behavior.