Assignment
State Management Day-08
What to Debug & How to Debug
Powered By GitBook
Next Stop - React Router | SPA
React doesn't come with a built-in router, but we can easily achieve routing with the react-router-dom library. Routing is how a web applications direct traffic.
Example: If you go to dataworld.com, you end up on my home page. If you go to dataworld.com/me, you're redirected to my about me page. If you go to dataworld.com/categories/javascript or dataworld.com/categories/css, you end up on a category listing page. The routes for these pages look something like this:
    / - root
    /:page_id - page
    /categories/:category_id - category
I'm not actually making a folder called categories and filling it with a bunch of files like javascript.html or css.html, I just have one template and the router knows to direct to the proper template. Once it gets to the template, it can pull from the URL to know which variables to display - for example, JavaScript or CSS related posts.
This website also happens to be a Single Page Application (or SPA) - only one page is loaded, and every click to a new page loads some additional JSON data, but does not actually request a new resource like loading index.html and about-me.html would.
I'm going to show you how to set up a simple SPA in React with react-router-dom, and pull in data dynamically through the URL. Below is the source of the completed project if you get lost along the way.
Prerequisites

Installation

Create a new React app.
1
npx create-react-app react-router-example
2
Installing packages. This might take a couple of minutes.
3
Installing react, react-dom, and react-scripts...
Copied!
Our project has two dependencies - react-router-dom for the router, and axios for making API calls.
1
npm install react-router-dom axios
Copied!
or
1
yarn add react-router-dom axios
Copied!

Browser Router

To use react-router-dom, we need to wrap our entire App component in BrowserRouter. There are two types of routers:
    BrowserRouter - makes pretty URLs like example.com/about.
    HashRouter - makes URLs with the octothorpe (or hashtag, if you will) that would look like example.com/#about.
Let's use BrowserRouter.src/index.js
1
import React from 'react'
2
import { render } from 'react-dom'
3
import { BrowserRouter } from 'react-router-dom'
4
import App from './App'
5
6
render(
7
<BrowserRouter>
8
<App />
9
</BrowserRouter>,
10
document.querySelector('#root')
11
)
Copied!

Route and Switch

Now in App.js, we can decide on the routes we want to use and direct accordingly. We'll use Routeand Switch for this task.
    Switch - Groups all your routes together, and ensures they take precedence from top-to-bottom.
    Route - Each individual route.
App.js
1
import React from 'react'
2
import { Route, Switch } from 'react-router-dom'
3
// We will create these two pages in a moment
4
import HomePage from './pages/HomePage'
5
import UserPage from './pages/UserPage'
6
7
export default function App() {
8
return (
9
<Switch>
10
<Route exact path="/" component={HomePage} />
11
<Route path="/:id" component={UserPage} />
12
</Switch>
13
)
14
}
Copied!
We're matching the root route (/) to HomePage, and dynamically matching any other page to UserPage. I only have one route for this simple example, but you could do more like this:
1
<Switch>
2
<Route exact path="/" component={HomePage} />
3
<Route path="/:id" component={UserPage} />
4
<Route path="/categories" component={CategoriesPage} />
5
<Route path="/categories/:id" component={IndividualCategoryPage} />
6
</Switch>
Copied!
This would ensure that dataworld.com/categories would go to a page listing all categories, but dataworld.com/categories/javascript would go to a completely different template for the individual category listing.
In order to link to a page within the SPA, we'll use Link. If we used the traditional <a href="/route">, it would make a completely new request and reload the page, so we have Linkto help us out.src/pages/HomePage.js
1
import React, { Component } from 'react'
2
import { Link } from 'react-router-dom'
3
4
export default function HomePage() {
5
return (
6
<div className="container">
7
<h1>Home Page</h1>
8
<p>
9
<Link to="/taniarascia">taniarascia</Link> on GitHub.
10
</p>
11
</div>
12
)
13
}
Copied!
So now I'm going to my first route, the root route which is loading HomePage, and I see the content and the link.
Could not load image
router home page

Dynamic Route Parameter

Our Link is navigating to /dataworld, which will match the /:id parameter in Route. In order to dynamically get the content from the URL - in this case, taniarascia - we'll use match.params.idfrom the props.
I'm going to use that parameter to make a call to the GitHub API and retrieve my data. In this example I'll be using Hooks, so if you're not familiar with them, please read Building a CRUD App with Hooks.src/pages/UserPage.js <props.match.params.id>
1
import React, { useState, useEffect } from 'react'
2
import axios from 'axios'
3
4
export default function UserPage(props) {
5
// Setting initial state
6
const initialUserState = {
7
user: {},
8
loading: true,
9
}
10
11
// Getter and setter for user state
12
const [user, setUser] = useState(initialUserState)
13
14
// Using useEffect to retrieve data from an API (similar to componentDidMount in a class)
15
useEffect(() => {
16
const getUser = async () => {
17
// Pass our param (:id) to the API call
18
const { data } = await axios(`https://api.github.com/users/${props.match.params.id}`)
19
20
// Update state
21
setUser(data)
22
}
23
24
// Invoke the async function
25
getUser()
26
}, []) // Don't forget the `[]`, which will prevent useEffect from running in an infinite loop
27
28
// Return a table with some data from the API.
29
return user.loading ? (
30
<div>Loading...</div>
31
) : (
32
<div className="container">
33
<h1>{props.match.params.id}</h1>
34
35
<tab
36
<tbody>
37
<tr>
38
<td>{user.name}</td>
39
<td>{user.location}</td>
40
<td>
41
<a href={user.blog}>{user.blog}</a>
42
</td>
43
<td>{user.followers}</td>
44
</tr>
45
</tbody>
46
</table>
47
</div>
48
)
49
Copied!

Last modified 2yr ago