DEV Community

Discussion on: 4 Ways to Render JSX Conditionally in React

Collapse
 
brense profile image
Rense Bakker • Edited

This is more or less my preferred way as well. However it is good to note that the component you pass as children will still be mounted (but not rendered) even if the condition is false. The only way to avoid the component being mounted is to have the condition and the component initialization in the same place.

function AlwaysMounted({condition, children}:React.PropsWithChildren<{condition:boolean}>){
  return !!condition ? children : null
}

const myCondition = false

// MyComponent will always be mounted (but not rendered)
return <AlwaysMounted condition={myCondition}><MyComponent /></AlwaysMounted>

// This is the only way to not mount your component if the condition is false
return !!myCondition ? <MyComponent /> : null
Enter fullscreen mode Exit fullscreen mode