Conditional Rendering with React Server Components
Illustrate conditional rendering within a React Server Component, rendering different components or content based on server-side logic or data.
// ServerComponent.js
import { db } from './database';
import AdminPanel from './AdminPanel.server';
import UserDashboard from './UserDashboard.server';
import GuestWelcome from './GuestWelcome.server';
export default function ServerComponent({ user }) {
let content;
// Perform server-side logic to determine what to render
if (user) {
if (user.isAdmin) {
// Render AdminPanel for admin users
content = <AdminPanel user={user} />;
} else {
// Render UserDashboard for logged-in users
content = <UserDashboard user={user} />;
}
} else {
// Render GuestWelcome for guests
content = <GuestWelcome />;
}
// Return the chosen content
return content;
}
This is a React Server Component that conditionally renders different components based on user information. It uses server-side logic to determine if a user is logged in, and if they are, whether they are an admin. Depending on the user's status, it renders an AdminPanel, UserDashboard, or a GuestWelcome component.