Basic Navigation
You can read full guide and tutorial here
Components in React Router V6
BrowserRouter
BrowserRouter is main component to cover allour React application to make it routable.
- Used for applications with a modern browser that supports the HTML5 history API.
- Allows you to use regular URLs (e.g.,
/about
) for navigation.
import { BrowserRouter, Routes} from 'react-router-dom';
<BrowserRouter>
<Routes>
...
</Routes>
</BrowserRouter>
Route
-
Used to declare a route and specify the component to render when the route matches the current location.
-
path
: Specifies the URL path for the route. -
component
: Specifies the React component to render when the route is matched.
import { Route } from 'react-router-dom';
<Route path="/about" element={About} />
Routes
-
Control all path in the React application we will use Route component in this Routes component.
import {Routes, Route } from 'react-router-dom';
<Routes>
<Route path="/about" element={About} />
...
</Routes>
useNavigate
-
Directly redirect to page to specific URL
import { useNavigate } from 'react-router-dom';
const navigate = useNavigate();
navigate('/another-page');
LinkuseParams
-
Used to
createaccessthepathlink,parameters,when click to link URLwe willchangelearn this in next chapter (dynamic routing) -
toimport { useParams} from 'react-router-dom'; let { id } = useParams();: Specifies the URL path that will redirect to
LinkuseSearchParams
-
Used to
createget thelink,querywhenparamsclick to linkin URLwill(somechangeurl might attach some data after "?" sign) -
Ex.
to/search?query=example:Specifieswill have query parameterquery
and theURLvaluepathisthat will redirect toexample
.
import { useSearchParams } from 'react-router-dom';
const [searchParams] = useSearchParams();
const queryId = searchParams.get('id');
useLocation
-
useLocation
will return information of current URL such as :pathname
path of current URLsearch
query parameters in current URL ex. "?id=123&name=John".hash
hash fragment in URL เช่น "#section-2".state
state datanavigate
from another page.
import { useLocation } from "react-router-dom";
const location = useLocation();
console.log(location);
Link
-
Used to create the link, when click to link URL will change
-
to
: Specifies the URL path that will redirect to
Reference : https://medium.com/@pratya.yeekhaday/reactjs-ทบทวน-react-router-dom-v6-สำหรับ-typescript-ec1b7e3427b7