← LOG/TECHNOLOGY/ENTRY N° 125

[How-To] Solve Dropdown Menu (select) does not work with React

A short introduction on how to assign the default value to drop down menu on react component.

FILED
READ
1 MIN
CATEGORY
TECHNOLOGY
TAGS
FRONTEND · JAVASCRIPT · REACTJS

I had this dropdown code. At first, nothing looks wrong with below code. But no matter what I do, the defaultValue wasn’t being set in the select options.

<select
  name="game_set_id"
  className="form-control"
  defaultValue={props.currentGameSetId}
  onChange={e => props.onChange(parseInt(e.currentTarget.value))}
  required
>
  <option value="">-- กรุณาเลือก Game Set --</option>
  {props.gameSets.map((gameSet: SetAsOption) => (
    <option key={gameSet.name} value={`${gameSet.id}`}>
      {gameSet.name}
    </option>
  ))}
</select>

After fiddling around and doing a google search I came across the simple solution.

Change the defaultValue to value. And it worked perfectly.

For now, it’s working fine and happy with it. When, I have sometime, I will try to fiddle around and find why it works with only value and not with defaultValue.

■ END OF ENTRY 125