Changing a Component return for Different Pages - Next.js

Summary

If you’re programming a site with a highly stylized design it’s likely some of your components will need to change depending on what page the user navigates to.

Web

Category:

Web

Date:Jan 18, 2023

Component Return blog post image

If you’re programming a site with a highly stylized design it’s likely some of your components will need to change depending on what page the user navigates to. This could be anything from a text color change to adding completely new elements. I wanted to share a simple navbar component that returns differently based on next/router’s pathname property.

This code can be used to conditionally render two completely different components for each page, it doesn’t have to be the nav specifically 🙂

First let’s import next/router and set up a component function:

import { useRouter } from "next/router";
const Navbar = () => {
}
export default Navbar

Next we’re going to set up the router to use in our return:

const Navbar = () => {
const router = useRouter();
const [altNav, setAltNav] = useState(false);
}

After we do this we can set up our return using the pathname property:

return (
<>
{router.pathname === '/our-services' ?
(
<nav> </nav>
)
:
(
<nav> </nav>
)
</>
);

We’re using conditional operators to check if the user is on the Our Services page. If they’re not on that page the default will return.

This simple code allows us to create two entirely different navigations based on what page the user navigates to. This gives us a lot of flexibility with what we can display.

💡 Adding the modified component to additional pages

We could call it a day here if we only wanted to see the alternate navbar on a single page, but what if we wanted to see the alternate nav on the blog too? That’s not too hard at all. By modifying the first condition in our operator we can check for multiple pages.

{router.pathname === '/our-services' || router.pathname === '/blog' ?

Now our special navbar is rendering on the blog page too 🎉

I hope you found this helpful when trying to add a conditional component return on your site.

Related Articles