Taking Advantage of React Routes
When working on an app, routes can allow distribution of the data you want to show on your app, organizing your app into “sections”. The first thing to do in order to use routes is to install “react-router-dom”.
Next is to import it either in your App.js or, what I like to do is to put it in index.js:
Putting <Router>
in index.js however, allows less lines in your App.js.
Next, depending on whether you are using class or functions, you add <Switch>
, <Route>
, and optionally <Link>
inside a <div>
.
Within the <Route>
, the exact path='/'
gives my root path as my Login page containing various functions as props including my user information as well as my loginStatus. Depending on what props you want to pass down from App.js, you can pass them here. What’s happening is that your app uses the root url: ”http://localhost:3000"
or ”3001"
, then adds the exact path='/' or /about.
Now, wherever you add a <Link to='/about>
(other ways to do this), your app can “route” to that page:
React has many components and container files to spread out the workload, meaning that a single component generally has one job. In this sense, routes allows us to utilize this ideal to create a more categorical and organized app flow.
The biggest advantage of using routes in my opinion is the ability to go to a specific page for a specific object. For example, in my recent capstone project, I had a page that rendered the Premier League teams in card format. Clicking on the Team Card routed the page to that specific team’s show page holding ONLY that specific team’s information.
As seen in the examples shown, routes can be very useful to implement into your app. Without them, your app will most likely be a single page that takes forever to scroll down due to all the information/data provided. Routes not only make it user friendly, but it makes life as developers a lot easier.