Reputation: 2907
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
Upvotes: 4
Views: 8915
Reputation: 77482
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>
}
}
Upvotes: 7
Reputation: 842
I would do it in List component. If your List component is large, i would put them in another helper file to require it.
Upvotes: 0