Have a simple drop down list being populated from an axios request. It is working outside of the fact that the actual selected item in the "Select a team" drop down does not persist when selected and the default value "Select a team" continues to show. What am I missing here, any help is greatly appreciated!
import KeeperTable from "./components/KeeperTable";
import { useState, useEffect } from "react";
import axios from "axios";
import { v4 as uuidv4 } from "uuid";
import "./App.css";
const App = () => {
const [selectedYear, setSelectedYear] = useState("");
const [selectedTeam, setSelectedTeam] = useState("");
const [managerList, setManagerList] = useState([]);
const handleChange = () => {
setSelectedYear(document.getElementById("ft-year-select").value);
setSelectedTeam(document.getElementById("ft-team-select").value);
};
useEffect(() => {
async function populateManagers() {
axios.get("/getManagers").then((res) => {
setManagerList(res.data);
});
}
populateManagers();
}, []);
return (
<div>
<div className="ddl-container">
<div className="ddlStyle">
<select onChange={handleChange} id="ft-year-select">
<option default value="#">
Select a Year
</option>
<option value="2020">2020</option>
<option value="2021">2021</option>
</select>
</div>
<div className="ddlStyle">
<select onChange={handleChange} id="ft-team-select">
<option default value="#">
Select a Team
</option>
{managerList.map((e) => {
return [
<option key={uuidv4()} value={e.manager}>
{e.manager}
</option>,
];
})}
</select>
</div>
</div>
<KeeperTable yearSearch={selectedYear} teamSearch={selectedTeam} />
</div>
);
};
export default App;
Adding a screenshot for referance. Here you can see that the manager "Dan" is selected yet his name doesn't appear in the input.
CodePudding user response:
You do not explicitly mark as selected any option
, and since you do key={uuidv4()}
for each one, it means than on each re-render the options are considered different that then previous render, and so do not keep their default highlight.
You will need to mark the selected one with
{managerList.map((e) => {
return [
<option key={uuidv4()} value={e.manager} selected={e.manager === selectedTeam}>
{e.manager}
</option>,
];
})}