Table of Contents
npm install react-router-dom
1. BrowserRouter
<BrowserRouter>
acts as a context provider, allowing its children to use routing.
import React from 'react'
import ReactDOM from 'react-dom'
import { BrowserRouter } from 'react-router-dom'
import App from './App'
ReactDOM.render(
<BrowserRouter>
<App />
</BrowserRouter>,
document.getElementById('root')
)
2. Link, Switch, Route
- The navigation link,
to
, represents the target link and is rendered as<a>
in the DOM. - By default,
path
matches from the beginning of the given path, whileexact
requires an exact match. - When passing
component
, props cannot be received, but usingchildren
allows props to be passed. Link
can be used anywhere and simply serves as a navigation link.Switch
can be thought of as aswitch
statement in flow control, rendering the corresponding component based on the current path.- It is usually written in a separate
Navigator.jsx
file.
Navigator.jsx
import { Link, Switch, Route } from 'react-router-dom'
import Home from './Home'
import About from './About'
const Navigator = () => {
return (
<Switch>
<Route exact path="/" component={Home} />
<Route exact path="/about">
<About />
</Route>
</Switch>
)
}
App.jsx
const App = () => {
return (
<div>
{/* shared navigation item component */}
<nav>
<Link to="/">Home</Link>
<Link to="/about">About</Link>
</nav>
{/* router component */}
<Navigator />
</div>
)
}
3. useParams
Dynamic routing consists of three steps:
- Configure the dynamic route variable in
Route
, then extract it usinguseParams
. - Dynamically generate
Link
. - In the detail page, use
useParams
to extract the route variable.
Navigator.jsx
import { Link, Switch, Route } from 'react-router-dom'
const Navigator = () => {
return (
<Switch>
<Route exact path="/">
<Home />
</Route>
<Route exact path="/subjects">
<SubjectList />
</Route>
{/* dynamic route based on subjectId */}
<Route path="/subjects/:subjectId">
<SubjectDetail />
</Route>
</Switch>
)
}
SubjectList.jsx
const SubjectList = () => {
const [subject, setSubject] = useState([])
useEffect(() => {
// API request
}, [])
return (
<div>
<h1>All Subjects</h1>
{/* dynamically generate Link */}
{subject.map((s) => (
<Link to={`/subjects/${s.id}`}>{s.title}</Link>
))}
</div>
)
}
SubjectDetail.jsx
import { useParams } from 'react-router-dom'
const SubjectDetail = () => {
const param = useParams()
const subjectId = param.subjectId // const {subjectId} = useParams
useEffect(() => {
// API request
})
return <div>{/* UI */}</div>
}
export default SubjectDetail
4. useHistory
Dynamic navigation, such as automatically redirecting after login, requires handling link changes within a function.
import { useHistory } from 'react-router-dom'
const Authentication = () => {
const history = useHistory()
const handleLogin = () => {
// user authentication...
history.push('/') // route to / page
}
return (
<form>
<input placeholder="User name" />
<input placeholde="Password" />
<button onClick={handleLogin}>Log In</button>
</form>
)
}
5. useLocation
To get the current path information:
pathname
is the current path name, useful for checking the current route.search
is the Query String in the URL, which appears after?
. It is commonly used for frontend filtering or sorting to display specific data.
{
"pathname": "/subjects",
"search": "?sort=date&page=1",
"hash": "",
"state": null,
"key": "qd3dcd5"
}
import { useLocation } from 'react-router-dom'
const SubjectList = () => {
const location = useLocation()
return (
<div>
<h1>All Subjects</h1>
</div>
)
}
6. Redirect
Login authentication with automatic redirection:
For each /private
route, if isLoggedIn
is true
, render <Private />
; otherwise, automatically redirect to /login
.
import { Link, Switch, Route, Redirect } from 'react-router-dom'
const App = () => {
const [isLoggedIn, setIsLoggedIn] = useState(false)
return (
<div>
<Link to="/">Home</Link>
<Link to="/private">Private</Link>
<Switch>
<Route exact path="/">
<Home />
</Route>
<Route exact path="/private">
{isLoggedIn ? <Private /> : <Redirect to="/login" />}
</Route>
<Route exact path="/login">
<Login />
</Route>
</Switch>
</div>
)
}
export default App