简体   繁体   中英

Conditional rendering from a functional component

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. 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?

i think you lost { to evaluate }

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

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.
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM