Next.js Discord

Discord Forum

Active link using useSelectedLayoutSegment in NextJS

Unanswered
Sun bear posted this in #help-forum
Open in Discord
Sun bearOP
Hi, how do i set bg color of active link using useSelectedLayoutSegment in nextjs? my code is working when i insert my pages inside the dashboard (ex. /localhost:3000/dashboard/course) but when i separate the folders from dashboard (ex. /localhost:3000/course) is not working anymore. Can someone help meee

11 Replies

can you provide more information?
what is "the folders from dashboard" and what route is "Sidebar" being used?
Sun bearOP
this is my architecture, but as you can see in the documentation of nextjs, the other pages are inside the dashboard (ref: https://nextjs.org/docs/app/api-reference/functions/use-selected-layout-segment#examples) The code is working when the other pages are inside the dashboard, but i want it to outside the dashboard,

like this:

localhost:3000/dashboard
localhost:3000/dashboard/course

i want to display sidebar in dashboard page, coruse page and forum page.
what i want to achive is to set the bg color of the active link, which is not working from the code above ><
So your sidebar is exported to 3 different routes?
Sun bearOP
Yesss ::
Why not put it in the root layout
That way you can access selectedLayoutSegments
The problem with selectedLayoutSegments is that it only detect inw level below
If your Sidebar is in /dashboard, it cant tell if you went to /forum or /course
One could argue if you decided to export ur sidebar, why not just hard code it which one is selected, but that wouldnt be efficient because you need to rerender your whole sidebar int he server
If your sidebar is in a common layout then not only you dont rerender the sidebar in the server at soft navigation, but you have access to selectedLayoutSegments()