Mark Ku's Blog

How Routing Works

The core principle of routing is to dynamically load the corresponding component based on the URL request.

Installing React Router (Most Common)

npm install react-router-dom --save // 基於 react-router 實作的 lib 
npm install @types/react-router-dom --save-deve // 官方沒提供

Usage

React Router's usage is primarily composed of these three parts: BrowserRouter + Switch + Route

app.tsx
<BroserRouter>
<Switch>
    <Route exect path="/" component={HomePage} />
     <Route path="/sign" render={()=><h1>sign</h1>} />
    <Route render={()=><h1>404</h1>} />
     
 </Switch>
</BroserRouter>
  • exact - Strict, only takes effect on an exact match.
  • Switch - To prevent pages from stacking, use Switch. Only one page component will be active.
  • The 404 page should be placed last, so it only takes effect when no other routes match.

How to Pass Parameters via Routes

1. Using "?" to Pass Parameters

http://localhost:3000/product?id=5

2. Using Route Segments to Pass Parameters

http://localhost:3000/product/123456

Getting Route Parameters via RouteComponentProps

import React from "react";
import { RouteComponentProps } from "react-router-dom";

interface MatchParams {
  touristRouteId: string;
}

export const DetailPage: React.FC<RouteComponentProps<MatchParams>> = (
  props
) => {
//   console.log(props.history);
//   console.log(props.location);
//   console.log(props.match);
  return <h1>路游路線詳情頁面, 路線ID: {props.match.params.touristRouteId}</h1>;
};

Getting Route Parameter Info Across Components

When using React Router components, match, history, and location are available by default in the props of child components. However, if you need to pass this information across components:

  • Use App Context (you can refer to previous notes)
  • HOC (Higher-Order Components)
import React,{Component} from 'react'
import {withRouter} from 'react-router-dom' 
class App extends Component{
    console.log(this.props);  // {match: {…}, location: {…}, history: {…}, 等}
    render(){return (<div className='app'></div>)
    }
}
export default withRouter(App);  // 這里透遛WithRouter將路由參數傳入props中

  • Use a Hook function to get them (a simplified way)
import { useHistory, useLocation, useParams, useRouteMatch } from "react-router-dom";
const history = useHistory();
const location = useLocation();
const { touristRouteId }: MatchParams = useParams();
const match = useRouteMatch();

There are two main ways to navigate in React:

1. history.push

<Button onClick={() => history.push("signIn")}>登入</Button>
<Link to={`detail/${id}`}>
  連結      
</Link>

To be continued

Author

Mark Ku

擁有 10+ 年經驗的資深軟體工程師,現為 AI 應用 Builder,專注於大型平台架構與簡化複雜系統設計,從電商系統到訂閱與收費平台,結合 AI Agent、AI 整合與自動化開發,打造高效率且可持續演進的產品技術基礎。Read More

Found this useful?

The author's free tools, daily podcasts and newsletter are all here.

Mark Ku · This article is licensed under CC BY 4.0. Credit the author and link back to the original when reusing it.

Comments

Subscribe to Newsletter

Subscribe to get new posts delivered instantly — never miss a tech share.

By submitting, you agree to receive emails. You can anytime.

Popular Posts

View all
Mark Ku
··602

Oracle Cloud Always Free Tier: Linux Host and Static IP for a $0 Cloud Solution

Oracle Cloud Always Free Tier: Linux Host and Static IP for a $0 Cloud Solution
Mark Ku
··490

Say Goodbye to Postman's Fee Trap! A Hands-on Guide to Bruno, the Open-Source Git-Native API Testing Powerhouse.

Say Goodbye to Postman's Fee Trap! A Hands-on Guide to Bruno, the Open-Source Git-Native API Testing Powerhouse.
Mark Ku
··333

A Free, Open-Source, Notion-like Knowledge Base — A Complete Guide to Deploying and Backing Up Outline Wiki

A Free, Open-Source, Notion-like Knowledge Base — A Complete Guide to Deploying and Backing Up Outline Wiki
Mark Ku
··264

Training Your Own AI Voice: Hardware Requirements, Open-Source Model Comparison, and LoRA Fine-Tuning

Training Your Own AI Voice: Hardware Requirements, Open-Source Model Comparison, and LoRA Fine-Tuning
Mark Ku
··221

Building an Efficient API Management Platform: Deploying Kong Gateway from Scratch - Part 1

Building an Efficient API Management Platform: Deploying Kong Gateway from Scratch - Part 1
Mark Ku
··215

Setting Up Samba on Ubuntu to Share Folders with Windows 11

Setting Up Samba on Ubuntu to Share Folders with Windows 11
React 學習筆記 - 路由 ( Router ) - Part's 5 - Mark Ku's Tech Notes