I am trying to build a modular dropdown list component in react. It also acts as a filter for a search app.
I created an object for all the types of dropdowns and their respective options as shown in the code below.
I then mapped the object and was able to make the component I wanted to.
The problem now is, I have to update changes made to the state of filters. But I cant pass the variable "val". It takes val literally and adds a new object member.
How do I fix it?
import React from "react";
export const FilterOptions = (props) => {
const types = {
gender: ["", "Male", "Female", "Genderless", "Unknown"],
status: ["", "Dead", "Alive", "Unknown"],
species: ["", "Human", "Alien"],
};
return (
<div className="flex flex-row">
{Object.keys(types).map((val, index) => {
return (
<div className="mx-4">
{val}
<select
name={val}
key={index}
onChange={(event) =>
props.setFilters({ ...props.filters, val(This variable here is the problem): event.target.value })
}
>
{types[val].map((type, index) => {
return (
<option key={index} value={type}>
{type}
</option>
);
})}
</select>
</div>
);
})}
</div>
);
};
CodePudding user response:
Use the square brackets:
props.setFilters({ ...props.filters, [val]: event.target.value })