Skip to main content

React router component

Components in React Router V6

BrowserRouter

BrowserRouter is main component to cover our 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.
  • You can define the path and element which will be render according to that path
import { createBrowserRouter, RouterProvider} from "react-router-dom";
import App from './App.jsx'
const router = createBrowserRouter([
  {
    path: "/",
    element: <App/>,
  },
]);

ReactDOM.createRoot(document.getElementById("root")).render(
  <React.StrictMode>
    <RouterProvider router={router} />
  </React.StrictMode>
);
  • Directly redirect to page to specific URL

  • Used to access path parameters, we will learn this in next chapter (dynamic routing)

  • import { useParams} from 'react-router-dom';
    
     let { id } = useParams();
  • Used to get the query params in URL (some url might attach some data after "?" sign)

  • Ex. /search?query=example will have query parameter query and the value is example.

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 URLe ex."#section-2".
    state state datanavigate from another page.