[英]How to add sub-options under options in select dropdown menu in react?
I am implementing a react app in which there is a dropdown menu with different options that are fetched from a dummy backend api using json-server
I am able to add options but I need to add sub-options that are also fetched from api.我正在实现一个反应应用程序,其中有一个下拉菜单,其中包含使用
json-server
从虚拟后端 api 获取的不同选项我可以添加选项,但我需要添加也从 api 获取的子选项。
Here's my db.json Api structure:这是我的 db.json Api 结构:
{
"groups":[
{
"key":"version",
"apis":["system_info","admin"]
},
{
"key":"admin",
"apis":["patients","doctors"]
},
]
}
In the above json respsonse keys
are the options and all the strings under apis
are to be sub-options.在上面的json中,respsonse
keys
是options,所有apis
下的string都是sub-options。
Here's my Dropdown menu implementation:这是我的下拉菜单实现:
import React from "react";
export default class ApiDropDown extends React.Component {
constructor() {
super();
this.state = {
options: []
};
}
componentDidMount() {
this.fetchOptions();
}
fetchOptions() {
fetch("http://localhost:5000/groups")
.then((res) => {
return res.json();
})
.then((json) => {
console.log(json);
this.setState({ options: json });
});
}
render() {
return (
<div >
<select className="togglebutton" >
<option selected disabled>Choose here</option>
{this.state.options.map((option, key) => (
<option key={key}>{option["key"]}</option>
))}
</select>
</div>
);
}
}
Api Response: Api 响应:
0: {key: "version", apis: Array(2)}
1: {key: "admin", apis: Array(2)}
This above dropdown is working for options but I need to implement sub-options.上面的下拉列表适用于选项,但我需要实现子选项。 Any idea how i can implement this?
知道如何实现吗?
Thanks!谢谢!
You can just fetch the suboption as you didn't for options.您可以只获取子选项,因为您没有获取选项。 And use the below code for the sub option.
并使用下面的代码作为 sub 选项。
render() {
return (
<div >
<select className="togglebutton" >
<option selected disabled>Choose here</option>
{this.state.options.map((option, key) => (
<option key={key}>{option["key"]}</option>
<optgroup label={option["key"]}>
{this.state.subOptions.map((subOption, key) => (
<option>{subOption.key}</option>
))}
// OR
{this.state.option["key"].subOptions.map((subOpt,i) => (
<option>{subOpt.i}</option>
))}
</optgroup>
))}
</select>
</div>
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.