How to render jsx calling non component function in React?

I adding return before jsx but it stops iteration

function App(){

  function recursion(object){
    for(let key in object){
      if(typeof object[key] === 'object'){
        <div>{key}</div>  // this jsx needs to render
        recursion(object[key])
      } else {
        <div>{key}</div>  // and this one
      }
    }
  }

  return {
    <>
      {recursion(someObject)}
    </>
  }
}

>Solution :

You need to return the JSX; it can’t just be lying around in the function. Something like this should do the trick:

function App(){

  function recursion(object){
    const ret = [];

    for(let key in object){
      if(typeof object[key] === 'object'){
        ret.push (
          <>
            <div>{key}</div>
            {recursion(object[key])}
          </>
        );
      } else {
        ret.push(<div>{key}</div>);
      }
    }

    return ret;
  }

  return (
    <>
      {recursion(someObject)}
    </>
  );
}

Leave a Reply