Create Application Navigation

Learn about application navigation, including how to create a navbar.

We'll cover the following

Application navigation

A non-trivial application should include the means for users to navigate across the numerous pages in the application. In a React application, react-router-dom is used for navigation. This lesson creates the navigation for the bookshop application. Earlier, we created some routes for navigation. We also created a ProtectedRoute component and an Authorized routes component that renders based on defined conditions.

Navbar creation

The application navbar for navigation can be found in the imports/ui/Navbar.js file. Opening this file should reveal that, on line 2, we import the Link component from the react-router-dom and the isAdmin function from the utility.js file.

The imported Link is an anchor tag that’s used to navigate between different components of the application. The Navbar components receive the authenticated, roles, and setAuth props from the App.jsx, which is its parent component. The authenticated prop is used to check the login status of the user, and the Navbar components render its links based on the user login status. The isAdmin function is used to render admin-only links, while the setAuth prop is a function that’s used to change the auth state of the AuthContext.

On lines 8–12, a logout function called logoutUser is defined. This function is attached to a Link anchor when a user is authenticated so that the user can log out from the application by clicking on it.

On line 54 of the App.jsx file, the Navbar component is added to the App component. Notice that the Navbar isn’t placed inside the Switch component of the router. This is so the Navbar will render on every route that’s visited at the very top of the page. Click “Run” to start the application.

Get hands-on with 1400+ tech skills courses.