Navigation Component using ‘useRouter’ hook in NextJS.

Deepak Kumar
2 min readFeb 23, 2023

--

Article Banner

NextJS offers a file-system based routing where each file under ‘pages’ directory is automatically added to the route which gives us ease to manage routing in NextJs.

Today, we’re going to create a side navigation (sidebar) using the ‘useRouter’ hook and Link component. Before heading further, I’d like to talk a bit about this hook.

useRouter hook is used to access the router object in any component (only functional) in your app where router object contains pathname, query object and many more information of the routing. For more details, visit here.

Getting Started

Create a sidebar.jsx or sidebar.js file in your component's directory, copy and paste the code mentioned below

Code & Approach Explanation

After importing useRouter hook and Link component, I’ve created an array which stores page names and their corresponding pathnames in objects.

In the main component, I’ve accessed the router object’s pathname property using useRouter hook and in the same line splitting the pathname by /. Pathname property is string which looks like this /page1 or /page1/id.

Now, in the markup section of the code, I’ve mapped our pages array to a sub-component Tabs passing pathName which looks likes ["","page1"] and object element of array as entry which contains nth page name and page route.

While inside the Tabs sub-component I’ve split the link property of the prop object data by / which contains nth page name and page route. In the second line of sub-component block, I’m checking if pathName’s 2nd element matches link’s 2nd element, then assigning null or active class to the constant depending upon matching pass.

Now, you might be thinking why I’m matching the first element of both split arrays rather than matching the whole pathname. This is because each page can have sub-routes such /page1/admin and we don’t need to match the entire route because our navigation component which only switch through main pages not the subpages. Thus, I’ve split pathName in the main component and link in the sub-component.

--

--

Deepak Kumar
Deepak Kumar

Written by Deepak Kumar

Graduate Frontend Engineer at Doorpix | Sometimes Code, Sometimes Write. On a journey to live a better life | https://dazzlerkumar.vercel.app/

No responses yet