Next.js Discord

Discord Forum

Adaptive page.tsx based on UserRole

Answered
Da_v_id posted this in #help-forum
Open in Discord
Hi!
What is the best strategy to adapt a page based on the user's, without changing the route (i.e. the route remainsdashboard/[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>;
}
Answered by James4u
yeah, conditional rendering by userRole
View full answer

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>}
}
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
@James4u there must be some other hacky ways but I would say conditional rendering will be just fine
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:
[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