Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Route Navigation

Route Navigation

In this chapter you will learn to use React Router v6 to implement page navigation without refresh, including dynamic routes and parameter reading.


Why Use Routing?

In traditional multi-page websites, every link click requires requesting a new page from the server, causing white-screen flicker.

Front-end routing lets JS control which component is displayed when the URL changes, without sending requests to the server.

Benefit: smooth switching, with an experience like a native app.


Core Concepts of React Router v6

Concept Purpose Corresponding Code
Route Table Define the mapping between URLs and components +
Router Outlet The placeholder position where child routes are displayed
Navigation Link Click to jump
Dynamic Route Variables in the URL /post/:id
Read parameters Get values from dynamic routes useParams()

Installation and Configuration



$ npm install react-router-dom@6

Creating the Route Configuration

Example

// File path: src/router/index.jsx

import

{

createBrowserRouter

}

from

'react-router-dom'

import

App from

'../App'

import

HomePage from

'../pages/HomePage'

import

PostPage from

'../pages/PostPage'

// createBrowserRouter creates a router instance

const

router

=

createBrowserRouter

(

[

 

{

    path

:

'/'

,

               

// App as the root layout

    element

:

<

App

/>,

children

:

[

     

{

        index

:

true

,

         

// index: true indicates the default child route for the / path

        element

:

<

HomePage

/>

}

,

{

path

:

'post/:id'

,

   

// Dynamic route: :id matches any value

        element

:

<

PostPage

/>

}

]

}

]

)

export

default

router

Two routing modes:createBrowserRouter produces clean URLs (/post/1) and requires server configuration. If the deployment environment is uncertain, use createHashRouter, which has a # in the URL (/#/post/1) and needs no server configuration.

Register Routes in main.jsx

Example

// File path: src/main.jsx

import

React from

'react'

import

ReactDOM from

'react-dom/client'

import

{

RouterProvider

}

from

'react-router-dom'

import

router from

'./router'

import

'./index.css'

ReactDOM.

createRoot

(

document.

getElementById

(

'root'

)

)

.

render

(

 

<

React.

StrictMode

   

{

/* RouterProvider injects the routes into the app */

}

   

<

RouterProvider router

=

{

router

}

/>

 

React.

StrictMode

)

Using Outlet in App.jsx

Example

// File path: src/App.jsx

import

{

Outlet

}

from

'react-router-dom'

import

NavBar from

'./components/NavBar'

import

'./App.css'

function

App

(

)

{

 

return

(

   

<

div className

=

"app"

     

<

NavBar

/>

<

main className

=

"container"

       

{

/* Outlet is the exit for nested routes: components matched by child routes are rendered here */

}

       

<

Outlet

/>

main

<

footer className

=

"footer"

       

<

p

©

2024

RUNOOB Blog.

Powered

by React.

p

     

footer

   

div

 

)

}

export

default

App


Link — Declarative Navigation

Link replaces the traditional tag and does not trigger a page refresh.

Example

import

{

Link

}

from

'react-router-dom'

function

BlogCard

(

{

id

,

title

,

summary

,

date

,

category

}

)

{

 

return

(

   

<

Link to

=

{

`

/

post

/

$

{

id

}

`

}

className

=

"card-link"

     

<

div className

=

"card"

       

<

span className

=

"tag"

{

category

}

span

       

<

h3

{

title

}

h3

<

p

{

summary

}

p

<

span className

=

"date"

{

date

}

span

     

div

   

Link

 

)

}

Do not use — it causes the browser to request a new page from the server, and the entire React app re-initializes. Use to switch on the client side without refresh.


useParams — Reading Route Parameters

In the detail page, you need to extract the article ID from the URL to find the corresponding article.

Example

import

{

useParams

}

from

'react-router-dom'

function

PostPage

(

)

{

 

// useParams returns an object containing the parameters in the URL

 

const

{

id

}

=

useParams

(

)

 

// Note: id is a string; when a number is needed you can convert with Number(id)

 

return

(

   

<

div

<

p

Current article ID:

{

id

}

p

   

div

 

)

}


useNavigate — Programmatic Navigation

In some scenarios you need to navigate without clicking a link (such as: navigating after form submission, or returning to the home page when an article is not found).

Example

import

{

useNavigate

}

from

'react-router-dom'

function

PostPage

(

)

{

 

const

navigate

=

useNavigate

(

)

 

const

article

=

null

 

// Assume the article was not found

 

if

(

!

article

)

{

   

// When the article does not exist, navigate back to the home page

   

return

(

     

<

div

<

p

Article does not exist

p

       

<

button onClick

=

{

(

)

=>

navigate

(

'/'

)

}

Back to Home

button

     

div

   

)

 

}

 

return

<

div

Article details...

div

}

Vue3 vs React Routing API Comparison

Function Vue3 React
Navigation Link
Router Outlet
Dynamic Route /post/:id /post/:id
Read parameters useRoute().params useParams()
Programmatic Navigation useRouter().push() useNavigate()

Hands-on: Complete Detail Page + Route Integration

Step 1: Modify BlogCard to Support Click Navigation

Example

// File path: src/components/BlogCard.jsx

import

{

Link

}

from

'react-router-dom'

function

BlogCard

(

{

id

,

title

,

summary

,

date

,

category

}

)

{

 

return

(

   

<

Link to

=

{

`

/

post

/

$

{

id

}

`

}

className

=

"card-link"

     

<

div className

=

"card"

       

<

span className

=

"tag"

{

category

}

span

       

<

h3

{

title

}

h3

<

p

{

summary

}

p

<

span className

=

"date"

{

date

}

span

     

div

   

Link

 

)

}

export

default

BlogCard

Step 2: Create HomePage and PostPage

Example

// File path: src/pages/HomePage.jsx

import

{

useState

,

useMemo

}

from

'react'

import

BlogCard from

'../components/BlogCard'

import

CategoryFilter from

'../components/CategoryFilter'

function

HomePage

(

)

{

 

const

[

articles

]

=

useState

(

[

   

{

id

:

1

,

title

:

'Complete Guide to React Getting Started'

,

summary

:

'Learn React from Scratch'

,

category

:

'React'

,

date

:

'2024-05-10'

,

      content

:

'

Why Learn React?

React is currently one of the most popular front-end frameworks...

'

}

,

   

{

id

:

2

,

title

:

'JS Asynchronous Programming Explained'

,

summary

:

'Understanding Promise and async/await'

,

category

:

'JavaScript'

,

date

:

'2024-05-08'

,

      content

:

'

What Is Asynchronous?

JS is single-threaded, and asynchronous operations keep the main thread unblocked...

'

}

,

   

{

id

:

3

,

title

:

'CSS Grid Layout in Practice'

,

summary

:

'Responsive Layout with Grid'

,

category

:

'CSS'

,

date

:

'2024-05-05'

,

      content

:

'

Getting Started with Grid

Grid is a two-dimensional layout system...

'

}

,

 

]

)

 

const

[

activeCategory

,

setActiveCategory

]

=

useState

(

'All'

)

 

const

categories

=

useMemo

(

(

)

=>

{

   

return

[

'All'

,

...

new

Set

(

articles.

map

(

a

=>

a.

category

)

)

]

 

}

,

[

articles

]

)

 

const

filteredArticles

=

useMemo

(

(

)

=>

{

   

if

(

activeCategory

===

'All'

)

return

articles

   

return

articles.

filter

(

a

=>

a.

category

===

activeCategory

)

 

}

,

[

articles

,

activeCategory

]

)

 

return

(

   

<

div

<

h2 className

=

"section-title"

Latest Articles

h2

     

<

CategoryFilter

categories

=

{

categories

}

activeCategory

=

{

activeCategory

}

onCategoryChange

=

{

setActiveCategory

}

/>

<

p className

=

"result-info"

Total

{

filteredArticles.

length

}

articles

p

     

{

filteredArticles.

length

===

0

?

(

       

<

p className

=

"empty-tip"

No articles in this category yet

p

     

)

:

(

       

<

div className

=

"article-grid"

         

{

filteredArticles.

map

(

article

=>

(

           

<

BlogCard key

=

{

article.

id

}

{

...

article

}

/>

         

)

)

}

       

div

     

)

}

   

div

 

)

}

export

default

HomePage

Example

// File path: src/pages/PostPage.jsx

import

{

useParams

,

Link

}

from

'react-router-dom'

import

{

useMemo

}

from

'react'

// Article data (later chapters will load it externally)

const

articles

=

[

 

{

id

:

1

,

title

:

'Complete Guide to React Getting Started'

,

category

:

'React'

,

date

:

'2024-05-10'

,

    content

:

'

Why Learn React?

React is currently one of the most popular front-end frameworks...

'

}

,

 

{

id

:

2

,

title

:

'JS Asynchronous Programming Explained'

,

category

:

'JavaScript'

,

date

:

'2024-05-08'

,

    content

:

'

What Is Asynchronous?

JS is single-threaded...

'

}

,

]

function

PostPage

(

)

{

 

const

{

id

}

=

useParams

(

)

 

// Find an article by ID

 

const

article

=

useMemo

(

(

)

=>

{

   

return

articles.

find

(

a

=>

a.

id

===

Number

(

id

)

)

 

}

,

[

id

]

)

 

// Article does not exist

 

if

(

!

article

)

{

   

return

(

     

<

div className

=

"not-found"

       

<

h2

Article does not exist

h2

       

<

p

Cannot find the article with ID

{

id

}

the article

p

       

<

Link to

=

"/"

Back to Home

Link

     

div

   

)

 

}

 

// Article exists

 

return

(

   

<

article className

=

"post-view"

     

<

span className

=

"category-tag"

{

article.

category

}

span

     

<

h1

{

article.

title

}

h1

     

<

time

{

article.

date

}

time

     

{

/* dangerouslySetInnerHTML is equivalent to Vue's v-html; beware of XSS risks */

}

     

<div className="content" dangerouslySetInnerHTML={{__html>

:

article.

content

}

}

     

/>

     

<

Link to

=

"/"

className

=

"back-link"

← Back to Home

Link

   

article

 

)

}

export

default

PostPage

dangerouslySetInnerHTML is the React version of v-html. The name is deliberately long to remind you: do not use it to render user input, as there is an XSS security risk. The content here is written by the developer, so it is safe.

Adding PostPage Styles

Example

/* File path: src/App.css, append detail page styles */

.post-view

{

 

max-width

:

720px

;

 

margin

:

0

auto

;

}

.category-tag

{

 

display

:

inline-block

;

 

padding

:

4px

12px

;

 

background

:

#e3f2fd

;

 

color

:

#1976d2

;

 

border-radius

:

12px

;

 

font-size

:

13px

;

 

margin-bottom

:

12px

;

}

.post-view

h1

{

 

font-size

:

32px

;

 

margin-bottom

:

12px

;

 

line-height

:

1.4

;

}

.post-view

time

{

 

display

:

block

;

 

color

:

#999

;

 

font-size

:

14px

;

 

margin-bottom

:

30px

;

}

.content

{

 

line-height

:

1.8

;

 

font-size

:

16px

;

 

color

:

#333

;

}

.content

h2

{

 

margin

:

24px

0

12px

;

 

font-size

:

22px

;

}

.content

p

{

 

margin-bottom

:

12px

;

}

.back-link

{

 

display

:

inline-block

;

 

margin-top

:

40px

;

 

color

:

#1976d2

;

 

text-decoration

:

none

;

}

.not-found

{

 

text-align

:

center

;

 

padding

:

60px

0

;

}


Chapter Summary

In this chapter you learned the core of React Router v6: route table configuration (createBrowserRouter), Link navigation, Outlet nested exit, dynamic route /post/:id, useParams for reading parameters, and useNavigate for programmatic navigation.

Now the blog has a real multi-page experience — browse the list on the home page, click to enter the detail page to read the full content.