Mapping checkboxes inside checkboxes ReactJS Mapping checkboxes inside checkboxes ReactJS reactjs reactjs

Mapping checkboxes inside checkboxes ReactJS


The issue is a recursive one. When an options group is displayed, the group checkbox and its options are displayed. When displaying the options, their type has to be taken into account.

  1. If the option is an ingredient, a simple checkbox can be displayed.
  2. If it is a group, a new options group has to be displayed with its options, like discribed above.

This is what is missing in your code. Here is a working sandbox and here is how you can fix it:

in Checkbox.js:

const input2Checkboxes =  this.props.options &&  this.props.options.map((item, index) => {    // Is the option a 'group' or an 'ingredient'?    return item.type === "group" ? (      {/* It's a group so display its options recursively */}      <Checkboxes        key={index}        name={item.name || item.description}        options={item.children}        childk={this.props.childk}        max={item.max}        min={item.min}      />    ) : (      {/* It's an ingredient so display a simple checkbox */}      <div className="inputGroup2" key={item.name || item.description}>        {" "}        <div className="inputGroup">          <input            id={this.props.childk + (item.name || item.description)}            name="checkbox"            type="checkbox"            onChange={this.selectData.bind(              this,              this.props.childk + (item.name || item.description)            )}          />          <label            htmlFor={this.props.childk + (item.name || item.description)}          >            {item.name || item.description}{" "}          </label>        </div>      </div>    );  });