Consider this React component that conditionally renders a message based on a boolean state.
import React, { useState } from 'react';
function Welcome() {
const [isLoggedIn, setIsLoggedIn] = useState(false);
return (
<div>
{isLoggedIn ? <h1>Welcome back!</h1> : <h1>Please sign in.</h1>}
</div>
);
}What will be rendered when this component first appears?
import React, { useState } from 'react'; function Welcome() { const [isLoggedIn, setIsLoggedIn] = useState(false); return ( <div> {isLoggedIn ? <h1>Welcome back!</h1> : <h1>Please sign in.</h1>} </div> ); }
Look at the initial value of isLoggedIn in the useState hook.
The state isLoggedIn starts as false. The ternary operator renders the second option, which is <h1>Please sign in.</h1>.
In React, you want to render a <p>Hello User</p> only if isUser is true. Which code snippet correctly does this?
function Greeting({ isUser }) { return ( <div> {/* Your code here */} </div> ); }
Remember that JSX expressions must be valid JavaScript expressions.
Option B uses the logical AND operator to conditionally render the paragraph only if isUser is true. Option B is also valid but the question asks for the && operator specifically. Option B is invalid syntax inside JSX. Option B renders the paragraph when isUser is false, which is incorrect.
Given this React component, what will be the displayed message after clicking the button two times?
import React, { useState } from 'react';
function ToggleMessage() {
const [show, setShow] = useState(true);
return (
{show && Visible
}
);
}import React, { useState } from 'react'; function ToggleMessage() { const [show, setShow] = useState(true); return ( <div> {show && <p>Visible</p>} <button onClick={() => setShow(!show)}>Toggle</button> </div> ); }
Each click toggles the show state between true and false.
Initially, show is true, so <p>Visible</p> is shown. Clicking once sets show to false, hiding the paragraph. Clicking again sets it back to true, showing the paragraph again.
Examine this React component:
function Example({ show }) {
return (
<div>
{show && if (true) <p>Hello</p>}
</div>
);
}What error will this code cause?
function Example({ show }) { return ( <div> {show && if (true) <p>Hello</p>} </div> ); }
JSX expressions must be valid JavaScript expressions, not statements.
The if statement is not allowed inside JSX expressions. This causes a syntax error.
In React, when you use conditional rendering with expressions like {condition && <Component />}, what happens if condition is false?
Think about how React treats boolean values in JSX.
When the condition is false, React renders nothing for that expression. The false value is ignored and does not produce any DOM output or error.