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 Redirect
component provided by React Router makes this easy! Like a Link
or NavLink
, the Redirect
component has a to
prop. However, once the Redirect
is rendered, the user will immediately be taken to the location specified by the to
prop:
import { Redirect } from 'react-router-dom' const UserProfile = ({ loggedIn }) => { if (!loggedIn) { return ( <Redirect to='/' /> ) } return ( // ... user profile contents here ) }
In this example, when the UserProfile
component renders, if the loggedIn
prop is false
, then the Redirect
component will be returned and then rendered, sending the user to the /
page. Otherwise, the component will render normally.
Instructions
Task 1
If you had been 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, import Redirect
from react-router-dom
.
Hint
You may either add Redirect
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 Redirect
to 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.