DEV Community

Discussion on: 4 Ways to Render JSX Conditionally in React

Collapse
 
adevinwild profile image
adil

For my part, in all my projects, whether personal or professional, I create an If component with a condition as property

It allows me to have something easier to read in my code


type Props = {
 children: ReactNode
 condition : boolean
}

 const IfComponent : FunctionComponent<Props> = ({ condition, children })=>{

   if(!!condition)
     return children

   return <></>
}
Enter fullscreen mode Exit fullscreen mode
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