0

I am trying to show menu where it can have parent child relationship, with flat structure it is working fine but with nested objects not able to do it. The below is the JSON and reactJS code. JSON -

{
  "data": [
    {
      "to": "#a-link",
      "icon": "spinner",
      "label": "User Maintenance"
    },
    {
      "content": [
        {
          "to": "#b1-link",
          "icon": "apple",
          "label": "System Controls"
        },
        {
          "to": "#b2-link",
          "icon": "user",
          "label": "User Maintenance"
        }
      ],
      "icon": "gear",
      "label": "System Preferences"
    },
    {
      "to": "#c-link",
      "icon": "gear",
      "label": "Configuration"
    }
  ]
}

ReactJS code -

export default class MenuComponent extends Component {
  constructor() {
    super();
    this.state = {}
  }

componentDidMount(){
  fetch('http://localhost:8084/Accounting/rest/v1/company/menu?request=abc')
  .then(response => response.json())
  .then(parsedJSON => parsedJSON.data.map(menu => (
    {
      to: `${menu.to}`,
      icon: `${menu.icon}`,
      label: `${menu.label}`
      // content: `${menu.content}`
    }
  )))
  .then(content => this.setState({
    content
  }))
}

  render() {
    console.log('333');
    console.log(this.state.content);
    return (
      <MetisMenu content={this.state.content} activeLinkFromLocation />
    )
  }
}

In JSON you can see the 'System Preference' has nested content.

kapil gupta
  • 335
  • 3
  • 19

1 Answers1

0

Try this code

 class MenuComponent extends Component {
  constructor() {
    super();
    this.state = {
    content : []
    }
  }

componentDidMount(){
  fetch('http://localhost:8084/Accounting/rest/v1/company/menu?request=abc')
  .then(response => response.json())
  .then(parsedJSON => parsedJSON.data.map(menu => (
    {
      to: `${menu.to}`,
      icon: `${menu.icon}`,
      label: `${menu.label}`
      // content: `${menu.content}`
    }
  )))
  .then(content => this.setState({
    content
  }))
}

  render() {
    const {content} = this.state
    if(content === undefined){
      return <div>Content not found</div>;
    }
    if(content.length === 0){
     return <div>Loading</div>;
    }
    return (
            <MetisMenu content={content} activeLinkFromLocation />
    )
  }
}
export default MenuComponent 
CodeZombie
  • 2,027
  • 3
  • 16
  • 30