Skip to main content

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>
  • Directly redirect to page to specific URL

  • Used to createaccess thepath link,parameters, when click to link URLwe will changelearn this in next chapter (dynamic routing)

  • toimport { useParams} from 'react-router-dom';
    
     let { id } = useParams();: Specifies the URL path that will redirect to

  • Used to createget the link,query whenparams click to linkin URL will(some changeurl might attach some data after "?" sign)

  • Ex. to/search?query=example: Specifieswill have query parameter query and the URLvalue pathis that will redirect toexample.

import { useSearchParams } from 'react-router-dom';

const [searchParams] = useSearchParams();
const queryId = searchParams.get('id');
  • useLocation will return information of current URL such as :
    pathname  path of current URL
    search 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);
  • 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