Learn

If you take anything away from this lesson, it should be that React Router treats everything as a component. To get fully comfortable using React Router in your code, you have to embrace this idea and the declarative coding style that follows from it. For the most part, this is pretty intuitive, but it can feel a bit counterintuitive when it comes to redirecting users.

To appreciate the declarative pattern, consider a common case for redirecting a user: a user wants to access a /profile page that requires authentication but is not currently signed in.

The Navigate component provided by React Router makes this easy! Like a Link or NavLink, the Navigate component has a to prop. However, where Link and NavLink must be clicked to navigate the user, once the Navigate component is rendered, the user will automatically be taken to the location specified by the to prop:

import { Navigate } from 'react-router-dom'; const UserProfile = ({ loggedIn }) => { if (!loggedIn) { return ( <Navigate to='/' /> ) } return ( // ... user profile content here ) }

In this example, when the UserProfile component renders, if the loggedIn prop is false, then the Navigate component will be returned and then rendered, sending the user to the / page. Otherwise, the component will render normally.

Let’s practice declaratively redirecting non-logged-in users in our application.

Instructions

Task 1

If you previously signed in, press the “Log Out” button. Then, manually navigate to http://localhost:3000/profile/ which will render the Profile component.

As you can see, the component will render but there will be no username to show. Instead, the Profile component should only be viewable if there is a user logged in and it should redirect the user to the SignUp page otherwise.

First, in Profile.js, import Navigate from react-router-dom.

Hint

You may either add Navigate to the existing list of imports or you can import it on its own.


Task 2

Now, above the return statement in the Profile component, return a Navigate that replaces the current URL with the path '/sign-up' if loggedIn is false.

Test that your code works by first making sure that you are signed out. Then by revisiting /profile. You should be redirected to the /sign-up page.

Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?