Reputation: 1222
I'm trying to create a dropdown list in a Form
using React and an existing array.
This is my team array:
const teams = [
{name: 'Arsenal', icon: arsenal, id: 1},
{name: 'Aston Villa', icon: villa, id: 2},
{name: 'Brighton & Hove Albion', icon: brighton, id: 4}
]
And now I have a Builder.js
, which returns several Form.Row
:
const StyledInput = styled(Form.Control)`
padding: 2px 5px;
width: 150px;
margin-right: 20px;
height: 50px;
`;
export default function Builder(){
const [teamA, setTeamA] = useState("Arsenal");
const [start, setStart] = useState("");
const [end, setEnd] = useState("");
return(
<Form>
<Form.Row>
<Form.Group controlId="startDate" bssize="large">
<Form.Label>Start Date</Form.Label>
<StyledInput
size="sm"
required
type="date"
value={start}
onChange={(e) => setStart(e.target.value)}
className="smaller-input"
/>
</Form.Group>
<Form.Group controlId="endDate" bssize="large">
<Form.Label>End Date</Form.Label>
<StyledInput
size="sm"
required
type="date"
value={end}
onChange={(e) => setEnd(e.target.value)}
className="smaller-input"
/>
</Form.Group>
</Form.Row>
<Form.Row>
<Form.Group controlId="teamA" bssize="large">
<Form.Label>Team A</Form.Label> <br />
<StyledInput
as="select"
required
className="smaller-input"
value={teamA}
onChange={(e) => {
setTeamA(teams[e-1].name);
}}
>
<option>{teams[0].name}</option>
</StyledInput>
</Form.Group>
</Form.Row>
<Button type="submit">Create</Button>
</Form>
);
}
However the dropdown list in this case just shows the first team, Arsenal. Eventually I would like to extend this to 20+ teams, so I would rather not declare them one by one in a Dropdown.Item
again. Is there a way to do this?
Upvotes: 0
Views: 196
Reputation: 186
Try using this map method:
<StyledInput
as="select"
required
className="smaller-input"
value={teamA}
onChange={(e) => {
setTeamA(teams[e-1].name);
}}
>
{
teams.map((team) => {
return <option>{team.name}</option>
})
}
</StyledInput>
Upvotes: 1