DEV Community

Cover image for Transform your navbar into a design resembling that of Google's navbar with React and Tailwind CSS.
Jyothikrishna
Jyothikrishna

Posted on • Updated on

Transform your navbar into a design resembling that of Google's navbar with React and Tailwind CSS.

Greetings everyone, I am Jyothikrishna and I am thrilled to demonstrate to you how to create a navbar that resembles Google's navbar using React and TailwindCSS.

As a developer, I know the importance of creating a user-friendly interface, and the navbar is one of the most crucial elements of any website. With Google's navbar being a popular design that users are familiar with, it's a great way to improve the user experience of your website.

In this article, I'll walk you through the steps needed to create a navbar that looks like Google's, including adding dynamic styling based on the user's scroll position. Let's get started!

To begin the process of creating a Google-like navbar, let's first describe its features. Specifically, the navbar should initially have a border at the bottom when page is not scrolled, and as the user begins to scroll, a shadow should be added to the bottom of the navbar. You can find a working demo here and you can grab the source code on github.

Creating the basic skeleton

I have created a basic navbar with a h1 and some links. Don't forget to wrap text inside li with Link component provided by the framework you are using.

code snippet for basic structure for navbar

Determining when to show the shadow

To determine if the user has scrolled or not, we can inspect the value of the scrollY key on the window object. Because our navbar needs to respond to changes in scrollY, we should store whether to show a shadow or not in a state variable.

code snippet for determining when to show shadow

We need to attach an event listener to the window object, which will update the showShadow state variable to true as soon as scrollY becomes a non-zero value. Conversely, when scrollY becomes zero, i.e., when the user scrolls to the top of the page, we should set the showShadow variable to false.

Remember to remove the event listener when the NavBar component is unmounted.

Code snippet for event listner

Adding Shadow conditionally

Change the nav element's className attribute to the following 👇

Code snippet showing how to add classes conditionally

You may be wondering why we are keeping the border-b class even when showShadow is true. The reason is that the border-b class increases the height of our navbar by 1px. If we remove the border-b class, the content inside our navbar will shift slightly.

Code for the whole navbar

That's it folks, you have made a navbar similar to Google's design 🥳🎉

Happy Hacking

Top comments (0)