Search code examples
javascripthtmljsonreactjscomponents

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.

Here's my db.json Api structure:

{  
  "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.

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:

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!


Solution

  • You can just fetch the suboption as you didn't for options. And use the below code for the sub option.

    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>
     );
    }