Use the React Router for a Single Page Application

Tram Ho

React does not have a built-in router, but we can easily install it with the react-router-dom library. Routing is the way the web redirects.

For example, if you visit taniarascia.com , you will go to taniarascia.com homepage. If you go to taniarascia.com/me , you will be redirected to the “about me” page. If you visit taniarascia.com/categories/javascript or taniarascia.com/categories/css , you will go to the category list page. The route will be as follows:

This website is also an SPA, only 1 page will load and every click to the new page will load some additional JSON data, but not really request resources from index.html and about-me.html. I will show you how to install a simple SPA with React with react-router-dom, and pull data via URLs. You can see the source code here :

Before reading this article, you should read:

Setting

Create a new React app

The project has 2 attachments, react-router-dom for the router and axios for API calls:

Or

BrowserRouter

To use react-router-dom , we need to wrap the entire App component in BrowserRouter. There are 2 types of routers:

Let’s use BrowserRouter

Router and Switch

In the App.js file, we can decide which routes we want to use and navigate accordingly. We will use Route and Switch for this section.

  • switch – group all routes together, and make sure they are prioritized from top to bottom.
  • route – each route individually

We are leaving the root (/) as HomePage, and automatically matching other pages with UserPage. I only have 1 route for this simple example, but you can do more:

This ensures that taniarascia.com/categories will lead to a list of category pages , but taniarascia.com/categories/javascript will lead to a completely different template for category listings.

Link

To link to another SPA page, we use the Link tag. If we use the <a href="/route"> tag, it will create a new request and reload the page, and Link helps us to do this.

Now go to the first route, root is loaded in HomePage, and see the following content as shown below.

Dynamic Route Parameter

Link to navigate to / taniarasca, where will match with /: id in Route. To be flexible in getting the content from the URL – in this case, taniarasca – we will use match.params.id from the props.

I will use param to make a call to the Github API and get data. In this example, I will use Hooks, so if you are not familiar with them, you can read the article Building a CRUD App with Hooks .

Conclude

If you missed something in the post, you can view the source here

Source: https://www.taniarascia.com/using-react-router-spa/

Chia sẻ bài viết ngay

Nguồn bài viết : Viblo