Adaptive page.tsx based on UserRole
Answered
Da_v_id posted this in #help-forum
Da_v_idOP
Hi!
What is the best strategy to adapt a page based on the user's, without changing the route (i.e. the route remains
layout.tsx (i have the user :
dummy version of the members' dashboard.tsx:
dummy version of the admins' dashboard.tsx:
What is the best strategy to adapt a page based on the user's, without changing the route (i.e. the route remains
dashboard/[team_id]
) ? In other terms, I am trying to create a dashboard that varies between roles within a team (member, admin, coordinator
).layout.tsx (i have the user :
export default async function Layout({
children,
}: {
children: React.ReactNode;
}) {
const userRole = await getUserRole();
return (
<div>
<header>
<h1>Welcome, {userRole}!</h1>
</header>
<main>{children}</main>
<footer>
<p>Footer content here</p>
</footer>
</div>
);
}
dummy version of the members' dashboard.tsx:
export default function MemberPage() {
return <div>This is a member Dasboard</div>;
}
dummy version of the admins' dashboard.tsx:
export default function MemberPage() {
return <div>This is an Admin Dasboard</div>;
}
10 Replies
i guess my approach to this would be rendering the roles based components via a function so you go like function(){
if(admin){return <div></div>
if(user){return <div></div>}
}
if(admin){return <div></div>
if(user){return <div></div>}
}
And then having the things you can render without the roles in the normal return from you page.tsx
have to say only working with Nextjs for a year now so dont know if their is a better way to do it π
yeah, conditional rendering by userRole
Answer
there must be some other hacky ways but I would say conditional rendering will be just fine
Da_v_idOP
If you find a link to other hacky ways could you please share those?
Also how would you organize the components if i have a structure like this:
would you do something like this?
but there must be cleaner ways to do it for sure
Also how would you organize the components if i have a structure like this:
[projectId]
βββ layout.tsx
βββ dashboard
βββ page.tsx (this should render the different dashboards depending on the three roles - member, admin, coordinator)
would you do something like this?
[projectId]
βββ layout.tsx
βββ dashboard
βββ page.tsx (orchestrate renders based on the role)
βββ _adminWidgets ( non routable folder containing widgets that will be rendered to admin)
βββ _memberWidgets (non routable // // // be rendered to member)
but there must be cleaner ways to do it for sure
well by hacky way, I just meant having seperated routes for different user role, and use
rewrites
to those routes depending on the user rolethen for the same path, you will have different pages
and regarding the components, it's okay to have components under page folder but I have been using
components
directorythere is no "correct" approach organizing your components