React conditional rendering
Created By: chatGPT
Conditional rendering in React allows you to display components or elements based on certain conditions. This is useful when you want to control what users see depending on the state of your application. You can use standard JavaScript operators such as
if
, ternary operators
, or logical &&
to achieve this.function RenderComponent() {
const isLoggedIn = true;
return (
<div>
{isLoggedIn ? (
<h1>Welcome Back!</h1>
) : (
<h1>Please Log In</h1>
)}
</div>
);
}
You can also use logical AND (
&&
) to conditionally render components. This is especially useful for rendering elements when the condition is true and doing nothing when it's false.function Notifications({ messages }) {
return (
<div>
{messages.length > 0 && <span>You have {messages.length} new messages.</span>}
</div>
);
}
Inline conditional rendering using the ternary operator can help you keep your code concise, while
if
statements can be used for more complex logic.function UserGreeting({ user }) {
if (user) {
return <h1>Hello, {user.name}!</h1>;
}
return <h1>Please sign up.</h1>;
}
Another way to manage conditional rendering is via component state. You can toggle between different states to display various components.
function ToggleMessage() {
const [showMessage, setShowMessage] = useState(false);
return (
<div>
<button onClick={() => setShowMessage(!showMessage)}>Toggle Message</button>
{showMessage && <p>Here is a conditional message!</p>}
</div>
);
}