Miklas Fafara
Miklas Fafara

Reputation: 11

UPD: React doesn't return HTML elements from functions

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;

Upvotes: 1

Views: 250

Answers (1)

Zuhair Naqi
Zuhair Naqi

Reputation: 1270

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>;
  }

Upvotes: 1

Related Questions