1

I need to create a nested accordion menu from JSON in the React.Component. Every key of the object of objects have to be the button which shows nested items on click (if the value is not null). I have two functions that create buttons for keys and hidden divs for values but they don't appear in HTML code.

menuItems.json

{
  "item1": {
    "nestedItem1": null,
    "nestedItem2": {
      "deeplyNetstedItem1": null
    }
  },
  "item2": null,
  "item3": null,
  "item4": {
    "nestedItem3": null
  }
}

DropdownList.jsx (UPD)

import React from "react";

class DropdownList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: this.props.data
    };
    this.createListData = this.createListData.bind(this);
    this.createButton = this.createButton.bind(this);
    this.createHidden = this.createHidden.bind(this);
  }

  createButton = (item) => {
    return <button className='accordion'>{item}</button>
  }

  createHidden = (item) => {
    return <div className='panel'>{item}</div>
  }

  createListData = (data) => {
    for (let [key, value] of Object.entries(data)) {
      if (value && typeof(value) == "object") {
        console.log(key, value);
        this.createButton(key);
        this.createListData(value);
      } else {
        this.createHidden(key);
        console.log(key);
      }
    }
  }

  render() {
    return <div>{this.createListData(this.state.data)}</div>
  }
}

export default DropdownList;

App.js

import React from "react";
import DropdownList from "./DropdownList/DropdownList";
import data from "./menuItems.json";

function App() {
  return <DropdownList data={data} />;
}

export default App;

1 Answer 1

1

This will work

renderObject = obj => {
    return obj === 'object' ? Object.values(obj).map(val =>
      typeof val === 'object' ? (
        this.renderObject(val)
      ) : (
        <li>{val ? val : 'Any message'}</li>
      ),
    ) : <li>Any message</li>
  };
  render() {
    return <div>{this.renderObject(this.state.data)}</div>;
  }
Sign up to request clarification or add additional context in comments.

4 Comments

i need to output all items from object, this way outputs only keys
Okay so try this renderObject = obj => { return Object.values(obj).map(val => typeof val === 'object' ? ( this.renderObject(val) ) : ( <li>{val ? val : ''}</li> ), ); }; render() { return <div>{this.renderObject(this.state.data)}</div>; }
TypeError: Cannot convert undefined or null to object
I updated the above code try that, it will not give you error

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.