Why I Stopped Using “&&” for Conditional Rendering in React
I have been using the #javascript '&&' operator for conditionally rendering my react components. The value of the condition generally depends on the #react state or props.?
I recently found that the ‘&&’ operator often leads to bugs.
For Example look at the below code
In the above code,
When the condition is true, <MyComponent/> will be rendered
When the condition is false, <MyComponent/> won’t be rendered
I came to know that when the condition is either true or false (boolean value), then there won’t be any problem but when the condition is ‘0’ or ‘undefined’, in that scenario ‘&&’ operator throws some challenges.
For Example: When the condition is 0(Zero), then 0 is getting rendered in the UI & it is messing up the UI. UI of the above mentioned code(0 is getting unnecessarily)
When the condition is? ‘undefined’, then there will be an error getting thrown(Please see below for the error snippet).
That’s why I stopped using the ‘&&’ operator and switched to using the ternary operator.
Senior Software Engineer - React JS | Javascript | Typescript | Redux
2 年You can also write like this !!condition && <Component />
Software Engineer
2 年Thanks Siva Rajana