Home > Net >  How to render jsx calling non component function in React?
How to render jsx calling non component function in React?

Time:05-14

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)}
    </>
  }
}

CodePudding user response:

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)}
    </>
  );
}
  • Related