2

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?

4
  • You could instead write some ? <Comp /> : null or <>{some && <Comp />}</> Commented Nov 9, 2021 at 22:32
  • Yeah, I was thinking someBoolean ? <Component /> : null as alternative, but was hoping there was some other way Commented Nov 9, 2021 at 22:33
  • some ? <Comp /> : null is the proper way to do it. It's what React recommends and for good reason, it's not prone to short circuiting bugs where you could throw any falsey value into the JSX. Commented Nov 9, 2021 at 22:51
  • someBoolean ? <Component /> : null is the canonical way to handle this that I've seen and used. Otherwise within JSX interpolation you can use && like @rn3w's answer Commented Nov 9, 2021 at 23:07

2 Answers 2

2

i think you lost { to evaluate }

return (<>
          {someBoolean && <Component/>}
        </>)
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.