Search code examples
javascriptreactjsselectoptgroup

Reactjs dynamic optgroup with options


I'm trying to map over an array and create a select with optgroups and then its opts. However the following code will only output the optgroup;

<select name="clients">
  {this.props.clients &&
    this.props.clients.length > 0 &&
    this.props.clients.map((e, key) => {
      return (
        <optgroup key={key} label={e.name}>
          {e.projects.map((project, projectKey) => {
            <option key={projectKey} value={project.id}>
              {project.name}
            </option>;
          })}
        </optgroup>
      );
    })}
</select>

Any ideas how I can get the options output too?


Solution

  • your inner map() function is not returning any object. Add return just before your <option> element.

    <select name="clients">
        {this.props.clients && this.props.clients.length > 0 && this.props.clients.map((e, key) => {
            return <optgroup key={key} label={e.name}>
                {e.projects.map((project,projectKey) => {
                    return <option key={projectKey} value={project.id}>{project.name}</option>
                })}
            </optgroup>;
        })}
    </select>