Search code examples
javascriptarraysreactjsnestednested-loops

React JSX: rendering nested arrays of objects


I have a component with the following render:

  render() {
    const { policy } = this.props;
    let deployment = policy.Deployment;
    let value = policy.value;
    let policyLegend = deployment.policyLegend;
    let policyObj = this.valueToPolicy(policyLegend, value);
    console.log(policy);
    console.log(deployment);
    console.log(value);
    console.log(policyLegend);
    console.log(policyObj);
    return(
      <div>
        <Form onSubmit={ (event) => this.handleSubmit(event, this.props) }>
          {
            policyLegend.map(function(policy) {
              <div>
                <h3 key={ policy.id }>{ policy.displayName }</h3>
                {
                  policy.values.map(value => {
                    return(
                      <Form.Field key={ value.name }>
                        <label>{ value.displayName }</label>
                        <Checkbox toggle />
                      </Form.Field>
                    );
                  })
                }
              </div>
            })
          }
          <Button name={ 'Submit' } type='submit'>Submit</Button>
          <Button onClick={ this.props.onCancel }>Cancel</Button>
        </Form>
      </div>
    )
  }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

policyLegend is an array of objects with a 'values' array inside each object.

When my application builds, I receive no errors but nothing appears on my component page. I'm not sure where I'm going wrong and would appreciate any advice, thank you.


Solution

  • It's because you do not return anything inside the policyLegend map. Try this:

    {
        policyLegend.map((policy) => {
            return (
                <div>
                    <h3 key={ policy.id }>{ policy.displayName }</h3>
                    {
                        policy.values.map(value => {
                            return(
                                <Form.Field key={ value.name }>
                                    <label>{ value.displayName }</label>
                                    <Checkbox toggle />
                                </Form.Field>
                            );
                        })
                    }
                </div>
            );
        })
    }