DEV Community

Cover image for React - BrowserRouter and useNavigate
G Gokul
G Gokul

Posted on

React - BrowserRouter and useNavigate

BrowserRouter:

  • In React, BrowserRouter is a parent component provided by the react-router-dom library that enables client-side routing in web applications.
  • It acts as the "routing engine" by wrapping your entire application, allowing you to switch between different views or "pages" without triggering a full browser refresh.

React Router DOM:

  • react-router-dom is an npm library that enables navigation and routing in React web applications.
  • React Router DOM is an npm package that enables you to implement dynamic routing in a web app.
  • It allows you to display pages and allow users to navigate them.
  • It is a fully-featured client and server-side routing library for React.

Features of BrowserRouter:

  • Real URL Updates: Reflects navigation in the browser's address bar using the HTML5 History API (pushState / replaceState).
  • Back & Forward Support: Native browser history buttons work out of the box for seamless navigation. -Deep Linking: Users can bookmark, share, or directly access any route via its URL.
  • SEO-Friendly: Clean, readable URLs (e.g., /products/123) are indexable by search engines.
  • Server-Side Rendering Ready: Pairs well with SSR frameworks like Next.js for full-stack React apps.

Working:

Initialization of Browser Router:
When the application is loaded, the BrowserRouter component is wrapped around the entire app (typically at the top level).

URL Detection:

  • BrowserRouter uses the HTML5 History API to detect changes in the URL.
  • This allows React Router to manipulate the URL while keeping the page from reloading.
  • When a user navigates to a different route (e.g., clicking a or typing a URL), BrowserRouter listens for this URL change.

Matching the URL:
Inside BrowserRouter the Route components define which URL path corresponds to which component. For instance, when the URL is /about, a is matched.

Rendering Components:

  • After matching the URL to the corresponding Route, the associated component is rendered.
  • If the URL matches /about, the About component will be displayed.

Navigating Between Views:
When a user clicks a link, such as:
Go to About

Maintaining Application State:

  • Since the page doesn't reload, the application's state (like form data or user input) remains intact.
  • React will only re-render the relevant components, ensuring a seamless user experience.

History Management:
The BrowserRouter uses the browser's built-in history stack, so users can navigate backward and forward between different routes using the browser's back and forward buttons.

Dynamic Updates:
As the URL changes (either by user interaction or programmatically using the history object), BrowserRouter continues to handle the URL and re-render the app's UI accordingly, providing smooth transitions between views.

example code:

import './App.css'
import Home from './components/Home'
import About from './components/About'
import Contact from './components/Contact'
import { BrowserRouter, Link, Route, Routes } from 'react-router-dom'
function App() {
  return (
    <div>
      {/* <a href="/">Home</a>
      <a href="/about">About</a>
      <a href="/contact">Contact</a> */}
      <BrowserRouter>
      <Link to={"/"}>Home</Link>
      <Link to={"/about"}>About</Link>
      <Link to={"/contact"}>Contact</Link>
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/about" element={<About />} />
        <Route path="/contact" element={<Contact />} />
      </Routes>
      </BrowserRouter>
    </div>
  )
}
export default App
Enter fullscreen mode Exit fullscreen mode

BrowserRouter: The foundational wrapper that synchronizes your UI with the browser's URL bar using the HTML5 history API.
Routes: The container component that looks through all its child components to find a path that matches the current URL.
Route: The individual mapping block. It requires a path property (the URL) and an element property (the React component to show).
Link: The React equivalent of an HTML anchor tag. It updates the URL without causing a full page refresh.

useNavigate:

  • In React, useNavigate is a built-in hook from the React Router library that allows you to change the URL and navigate to different pages programmatically.
  • It is the modern replacement for the older useHistory hook used in React Router v5.

Why use useNavigate?

While you normally use a component for a user to click on, you use useNavigate when you need to redirect a user inside your JavaScript code after an event happens, such as:

  1. Redirecting a user to a dashboard after a successful login.
  2. Sending a user to a confirmation page after a form submission.
  3. Booting an unauthenticated user back to the login page.

preventDefault():

In React, event.preventDefault() is a method used to stop the browser's default behavior from happening when a specific event occurs.

example code:

import { useNavigate } from "react-router-dom"

function Home(){
    const navigate = useNavigate();
    function changeComponent(){
        navigate("/about")
    }
    function element(params){
        params.preventDefault();
    }
    return(
        <div>
            home
            <button onClick={changeComponent}>go to about</button>

            <form action="">
                <input type="text" placeholder="username" />
                <input type="password" placeholder="password" />
                <button onClick={element}>submit</button>
            </form>
        </div>
    )
}
export default Home
Enter fullscreen mode Exit fullscreen mode

Difference between useNavigate and Link:
n

Top comments (0)