Home > Software design >  Conditional rendering from a functional component
Conditional rendering from a functional component

Time:11-10

I'd like to conditionally render a React component like this:

parent.ts

   ...
   <Parent>
     <Child/>
   <Parent>
   ...

child.ts

   ...
   return (someBoolean && <Component/>)
   ...

I get a TypeScript error in child.ts that Its return type 'false | Element' is not a valid JSX element.

I want the conditional to be in child.ts, because it is used in other places as well, not just parent.ts. What's the appropriate way to do this? Would I have to settle for a ternary or if/else?

CodePudding user response:

i think you lost { to evaluate }

return (<>
          {someBoolean && <Component/>}
        </>)

CodePudding user response:

In my experience using hundreds of thousands of ternaries in React, I would recommend using it like

const A = () => {
  // Never in a form where it's easy to miss the ternary symbols
  // Leads to bugs...
  return (superUnderTip >= Math.pow(UserService.count(), 2)) ? 
  <ProviderTrainsFully lights={{hgih: 33}} rest={"too many null"} /> : null;

  // Always in this form so your brain can super easily scan for the
  // test and the output component.
  return (superUnderTip >= Math.pow(UserService.count(), 2))
    ? <ProviderTrainsFully lights={{hgih: 33}} rest={"too many null"} />
    : null;
    
  // Never in a nested ternary -- make child components for additional
  // conditional rendering.
}
  • Related