Chakra UI is a CSS-In-Js library that makes it really easy for React developers to code UI for their applications. It is easy to develop most of the common UI components with Chakra UI however it does get tricky sometimes.
One such scenario is creating a top fixed nav bar that enables users to access navigations in the header, while scrolling pages in the application that are longer than the viewport height.
Let's take a look at the steps to build one such fixed nav bar using Chakra UI.
Firstly, we need to fix the nav bar at the top and make sure that it is removed from the regular document flow. If not, the header will disappear on scroll just like any normal element. To achieve this we can use position property.
<Flex as="header" position="fixed" w="100%"> ... </Flex>
Let's add a top margin to the div that contains the rest of the document so that the application content starts after the header in the un-scrolled state. I have used Chakra UI components such as Flex for the header and Container for the rest of the application but any layout component can be used instead.
<> <Flex as="header" position="fixed" w="100%"> ... </Flex> <Container as="main" mt="20"> ... </Container> </>
Note: The top margin value depends on the height of elements in the header.
Next we can focus on making the nav bar stand out from rest of the page. For this we need to modify it's z-index to a value greater than other components in the application.
Note: A rational z-index value say 200 should do it for most use cases.
Lastly, we need to make sure that the navbar is painted over any underlying component on scroll. There's two ways to achieve this.
You can use an opaque background color for the header, which will hide the underlying elements completely on scroll. The final code for header, in this case, is as follows.
<> <Flex as="header" position="fixed" backgroundColor="white" w="100%"> ... </Flex> <Container as="main" mt="20"> ... </Container> </>
It is possible for the header to apply a blur effect to the underlying content on scroll, instead of hiding it completely. This can be achieved with the help of backdrop-filter and a translucent background color to the header like so.
<> <Flex as="header" position="fixed" backgroundColor="rgba(255, 255, 255, 0.8)" backdropFilter="saturate(180%) blur(5px)" w="100%"> ... </Flex> <Container as="main" mt="20"> ... </Container> </>
Disclaimer: I found out about the above approach through this website through induction.
Note: backdrop-filter property is not compatible with IE and Firefox at the time of writing this article. Hence do check out the Browser Compatibility section of the property in mdn docs before using it in production.
That's it. We have created a top fixed nav bar using Chakra UI.
Thank you for reading and do follow me for more such articles.