Building an Instagram Clone: Week 2 — Setting Up Routes
Defining Routes
The next step in the tutorial is to begin defining our routes. We will have five pages/routes: Dashboard, Login, Sign Up, Profile, and Not Found. Within our src
folder, we’ll create a folder called constants
that contains a file called routes.js
. In routes.js
, we will export const
s for each of the routes.
Implementing Lazy
Once these routes are defined, we can begin working on App.js
. In App.js
we will import lazy
and suspense
from React
. lazy
and suspense
are new tools to me — they are components that essentially tell us to wait for the code to load, but while we are waiting for the code to load, display a spinner/loading message/etc in the meantime. We will use lazy
to import our pages, but first, we must create these pages! In a new folder called pages
within src
, I created a file for a component for each of our routes.
Implementing Suspense
Since Suspense
is a component, we can wrap it around where we want to use it. In this case, we will use it in the return
of App.js
:
React Router Setup
Now that we’ve implemented our routes, lazy, and suspense, we must set up our react-router. We’ll need to import a few things in our App.js
such as BrowserRouter
and Routes
. Make sure that you’ve included react-router-dom
in your dependencies — I didn’t realize I hadn’t, and I got an error! Once everything was imported properly, I wrapped everything in our return
above in a <Router>
tag. This ensures that the router will apply to everything we put inside this tag, aka our application. Then within that, we wrap further content inside a <Switch>
tag which tells our code to check the routes for everything inside these tags. Now that we are ready to set up the routes, we can get rid of the filler <p>
tag that says “This is where our content will be” and replace it with the code for our routes like so:
Now, when we navigate to the URLs indicated for each route, we will get the page associated with it.