Skip to content
Advertisement

Default value is not displaying in select drop down box of react hooks app

In my react hooks select drop down, the default value is not displaying. On page load I would like to display Select Position in the drop down. Could someone please advise why it is not displaying the default value ?

code sandbox link: https://codesandbox.io/s/sad-diffie-kx9h49?file=/src/App.js:0-991

import "./styles.css";
import React, { useEffect, useState } from "react";

export default function App() {
  const [defaultValue, setDefaultValue] = useState("Select Position");
  const [positionType, setPositionType] = useState([
    "Goal Keeper",
    "Striker",
    "Attacking Midfielder",
    "Right Midfielder",
    "Defending Midfielder",
    "Left Midfielder",
    "Center Back",
    "Right Fullback",
    "Left Fullback"
  ]);

  useEffect(() => {
    setDefaultValue(defaultValue);
  }, []);

  const handlePositionTypeChange = (e) =>
    console.log(positionType[e.target.value]);
  return (
    <div className="App">
      <label>Position</label>
      <select
        defaultValue={defaultValue}
        onChange={(e) => handlePositionTypeChange(e)}
        key={defaultValue}
        className="browser-default custom-select"
      >
        {positionType.map((position, key) => (
          <option value={key}>{position}</option>
        ))}
      </select>
    </div>
  );
}

Advertisement

Answer

import "./styles.css";
import React, { useEffect, useState } from "react";

export default function App() {
  const [selectedValue, setSelectedValue] = useState("Select Position");
  const [positionType, setPositionType] = useState([
    "Goal Keeper",
    "Striker",
    "Attacking Midfielder",
    "Right Midfielder",
    "Defending Midfielder",
    "Left Midfielder",
    "Center Back",
    "Right Fullback",
    "Left Fullback"
  ]);


  const handlePositionTypeChange = (e) => {
    console.log("e.target.value", e.target.value);
    setSelectedValue(e.target.value);
  };
  return (
    <div className="App">
      <label>Position</label>

      <select
        value={selectedValue ? selectedValue : ""}
        onChange={handlePositionTypeChange}
        className="browser-default custom-select"
      >
        <option value="Select Position" disabled>
          Select a color...
        </option>
        {positionType?.map((position, key) => (
          <option key={key} value={position}>
            {position}
          </option>
        ))}
      </select>
    </div>
  );
}
CodeSandbox
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement