Home > Blockchain >  Is it a bad practice to conditionally render a component with "&&" in React?
Is it a bad practice to conditionally render a component with "&&" in React?

Time:09-18

In other words, is this:

const [condition, setCondition] = useState(true);

return (
   condition && <Component /> 
)

As good as this:

const [condition, setCondition] = useState(true);

return (
   condition ? <Component /> : null
)

In terms of bugs, rendering, etc.? Because I'm sure that using && to condition something like that in vanilla JavaScript is not recommended.

Thanks!

CodePudding user response:

No, it's not a bad practice;

these two snippets will behave exactly the same: no difference at all.

condition && <Component /> 
condition ? <Component /> : null 

why? in both case the output is a valid react child:

type ReactNode = ReactElement | string | number | ReactFragment | ReactPortal | boolean | null | undefined;

CodePudding user response:

Simply it depends, if the <Component /> is a very large component with a lot of content and you toggle a lot, it would be better to display: none than completely destroy it.

For example

<Component style={{ display: condition && 'unset' : 'none' }} /> 

Keep in mind, that the style here will be a prop that needs to pass to the root element of the component.

but if it's a small component, destroying and re-initializing it will not be a bad practice.

  • Related