javascript - REACT: JSON Tree with the help of Recursion -
the json backend guys provide me multiple parent child have put dynamic loop show parent child.
json
"data": [ { "id": 25, "slug": "mobiles", "parent_id": null, "name": "mobiles" }, { "id": 26, "slug": "mobile-phones-accessories", "parent_id": 25, "name": "mobile phones accessories" }, { "id": 27, "slug": "computer-laptop", "parent_id": null, "name": "computer & laptop" }, { "id": 28, "slug": "laptops", "parent_id": 27, "name": "laptops" }, { "id": 29, "slug": "mobile-phones", "parent_id": 26, "name": "mobiles phone" } ]
my function (kindly ignore this. it's try have got 1 child parent)
rendercategorieshtml() { const { categories } = this.props; if (!categories) return false; const nullcat = []; categories.map((obj) => { if (obj.parent_id == null) { nullcat.push(obj); } }); return nullcat.map( (parentcat, i) => ( <div classname="form-group" key={i}> <div classname="checkbox" key={i}> <label> <field name={`categories.${parentcat.id}`} component="input" type="checkbox" /> {parentcat.slug} </label> </div> { categories.map( (childcat, j) => ( parentcat.id == childcat.parent_id ? <div classname="checkbox ml-20" key={j}> <label> <field name={`categories.${childcat.id}`} component="input" type="checkbox" /> {childcat.slug} </label> </div> : '' ) ) } </div> ) ); }
i want (that dynamic html want)
<ul> <li>mobiles</li> <ul> <li>mobile-phones-accessories</li> <ul> <li>mobile-phones</li> </ul> </ul> <li>computer-laptop</li> <ul> <li>laptops</li> </ul> </ul>
try this:
class treerender extends react.component { state = { data: json.parse('[{"id": 25,"slug": "mobiles","parent_id": null,"name": "mobiles"},{"id": 26,"slug": "mobile-phones-accessories","parent_id": 25,"name": "mobile phones accessories"},{"id": 27,"slug": "computer-laptop","parent_id": null,"name": "computer & laptop"},{"id": 28,"slug": "laptops","parent_id": 27,"name": "laptops"},{"id": 29,"slug": "mobile-phones","parent_id": 26,"name": "mobiles phone"}]') } getcurrent = (node) => this.state.data.filter(cnode => cnode.parent_id == node).map(cnode => ( <ul key={`node_${cnode.id}`}> <li>{cnode.name}</li> {this.getcurrent(cnode.id)} </ul> )) render() { return ( <div> {this.getcurrent(null)} </div> ); } }
Comments
Post a Comment