I want to create a dynamic dropdown menu by reading data from the database. But I'm not sure how to implement a dropdown menu that shows data dynamically.
This is the react code that I have implemented.
export default function ItemAdd(){
const [inputs, setInputs] = useState({});
const [arry, setArry] = useState([]);
const [temp,setTemp] = useState();
const [user,setUser]=useState([]);
useEffect( ()=>{
try{
axios.get('http://localhost:8070/user/').then((res)=>{
setUser(res.data);
})
}catch{
console.error();
}
},[])
const addArry = async()=>{
setArry([...arry,temp]);
setInputs(values => ({...values, "arry": [...arry,temp]}));
}
const handleSubmit = async(event) => {
event.preventDefault();
console.log(inputs);
try {
await axios.post("http://localhost:8070/item/",inputs).then((res)=>{
if(res.status==201){
alert("create sucsesfull");
navigate("/display")
}
})
} catch (error) {
alert("create fail")
console.log(error)
}
}
This is the part that I have implemented the dropdown menu
return (
<div>
<form onSubmit={handleSubmit}>
<div>
<label>Enter item name:</label>
<input
type="text"
name="name"
value={inputs.name || ""}
onChange={handleChange}
/>
</div>
<label>Enter user:
</label>
<select onChange={(e)=>setTemp(e.target.value)}>
<option value={user.data._id}>{user.data.name}</option>
</select>
<button type="button" onClick={addArry}>add</button>
<br></br>
<div>
<button type="submit">Submit</button>
</div>
</form>
</div>
)
}
In the backend I have created all the routes and the database also connected. There are no issues in the backend.
CodePudding user response:
You, just map the user data you got from API inside the select tag and add multiple props in select tag for multi-select value
<select multiple onChange={"your onchange method"}>
{user.map((item) =>{
return <option value={item._id}>{item.name}</option>
})}
</select>
CodePudding user response:
I think you can use the select tag with map