Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React rendering nested json

Tags:

reactjs

I have some json looking like this

[
    {
    "name": "Hello Kitty",
    "items": [
        {
        "name": "Kitty Muu Muu"
      },
      {
        "name": "Kitty smack"
      }
    ]
  },
  {
    "name": "Hello Pussy",
    "items": [
            {
        "name": "World",
        "items": [
            {
            "name": "Hello Pussy world"
          }
        ]
      }
    ]
  }
]

it's nested JSON and my question is; where should the recursiveness be handled to render this?

I have 2 components List component that calls the data and posts data changes back to the server

Item component that renders a single item

Should I handle this at the list level or item level?

The item renders an input field you can update and this should be possible both at parent and child level

like image 529
kristian nissen Avatar asked Mar 12 '23 20:03

kristian nissen


1 Answers

You can use Item to show child items(in React you can do it with children property), however main work will be in List, for example

class Item extends React.Component {
  render() {
    return <li>
      { this.props.name }
      { this.props.children }
    </li>
  }
}

class List extends React.Component {
  constructor() {
    super();
  }

  list(data) {
    const children = (items) => {
      if (items) {
        return <ul>{ this.list(items) }</ul>
      }
    }

    return data.map((node, index) => {
      return <Item key={ node.id } name={ node.name }>
        { children(node.items) }
      </Item>
    });
  }

  render() {
    return <ul>
      { this.list(this.props.data) }
    </ul>
  }
}

Example

like image 50
Oleksandr T. Avatar answered Mar 21 '23 00:03

Oleksandr T.