Search code examples
jsonreactjsrecursiontreechildren

React - create recursive children


My issue is simple, i want to make a list from json recursively. What i have by now:

const jsonMenuConfig =[
            {
                main:"Li1",
                inside:[]
            },
            {
                main:"Li2",
                inside:[]
            },
            {
                main:"Li3",
                inside:[{main:"insideLi1",inside:[]},{main:"insideLi2",inside:[]},{main:"insideLi3",inside:[]}]
            }
        ];


class App extends React.Component{
  render(){
    return(
      <ListMaker tree={jsonMenuConfig}/>
    );
  }
}
function ListMaker(props){
  return props.tree !== undefined || props.tree.length > 0 ? 
          <ul>{
            props.tree.map((item)=>{
              return <li>{
                  item.main
                }{
                  <ListMaker tree={item.inside}/>
                }</li>
            })
          }</ul>
        : null
}
ReactDOM.render(
  <App/>,
  document.getElementById('app')
);

My main idea was to create function that could call itself and return deeper children only when children exist. I think that should work but i cant rid of ul's inside all li's. It seems ul should never be rendered inside first and second li becouse it doesn't fit this

props.tree !== undefined || props.tree.length > 0

What is happening right now :

<ul>
  <li>
    <ul></ul> -- empty, should never return
  </li>
  <li>
    <ul></ul> -- empty, should never return
  </li>
  <li>
    <ul></ul> ... -- children here, succes
  </li>
</ul>

What i simply want :

<ul>
  <li></li>
  <li></li>
  <li>
    <ul>
      <li></li> ... -- children here, succes
    </ul>
  </li>
</ul>

What can be possible wrong ? Can it be done better way ?


Solution

  • You have bad logic here. Change props.tree !== undefined || props.tree.length > 0 to props.tree !== undefined && props.tree.length > 0.

    || means or so if either condition is true it is going to evaluate to true and since props.tree is defined it is firing true.