CARVIEW |
Conditional Rendering In React
Here we will cover all the basic concepts of ReactJS like Rendering Components, Contitional Rendering and much more.
Question 1
Which of the following is the correct way to conditionally render a component in React without rendering false
or null
to the DOM?
{condition && <MyComponent />}
{condition ? <MyComponent /> : null}
{condition && condition}
{condition || <MyComponent />}
Question 2
Why is null
often used in conditional rendering?
It displays an empty
<div>
It triggers an error boundary
It prevents rendering anything
It replaces the component with
false
Question 3
Why can {count && <p>{count}</p>}
behave unexpectedly when count = 0?
It throws an error
It still renders 0
It doesn’t render anything
It duplicates the element
Question 4
Which is the correct way to return multiple elements conditionally?
{isValid && (<p>Hello</p> <p>World</p>)}
{isValid && [<p>Hello</p>, <p>World</p>]}
{isValid && (<><p>Hello</p><p>World</p></>)}
{isValid ? <p>Hello</p><p>World</p> : null}
Question 5
Why might {isOpen && <Modal />}
be preferred over {isOpen ? <Modal /> : null}
?
It’s more explicit
It produces smaller bundle size
It avoids null checks in React’s reconciliation
Both are functionally identical, but
&&
is cleaner
Question 6
What will be the output of the following code?
{
condition1 ? <Component1 /> :
condition2 ? <Component2 /> :
<DefaultComponent />
}
It will render <Component1 /> if condition1 is true, otherwise <Component2 /> if condition2 is true, otherwise <DefaultComponent />
It will render <Component1 /> if condition1 is true, otherwise <Component2 />.
It will always render <Component1 />
It will never render anything.
Question 7
In the following code, what will be rendered?
const userRole = 'admin';
return userRole === 'admin' && <AdminPanel/>;
null
undefined
<AdminPanel />
An error will occur
Question 8
How would you write a conditional rendering to display a "Loading..." message if isLoading is true and show Content if it is false?
{isLoading && "Loading..." || "Content"}
{isLoading ? "Loading..." : "Content"}
{!isLoading && "Loading..." ? "Content" : ""}
{isLoading && return "Loading..." : "Content"}
Question 9
What will be the output of the following?
<p>{count && "Items in cart"}</p>
Items in cart
0
Nothing
Error
Question 10
Which React syntax is used to conditionally render elements based on multiple conditions?
{
condition1 ? <First /> : condition2 ? <Second /> : <Third />
}
Switch case rendering
Ternary operator
&& operator
if statement
There are 10 questions to complete.