React Router

React Router

React Router is a standard library for routing in React applications. It enables the navigation among views of various components in a React application, allows changing the browser URL, and keeps the UI in sync with the URL

Key concepts

  1. Routes: routes are primary units of React Router.A route is defined by the ‘Route’ components,which maps a URL path to a specific component.

  2. Router Components: there are several types of router components:

  • ‘BrowserRouter’: uses the HTML5 history API(pushState,replaceState,and popstateevent) to keep your UI in sync with the URL.

  • ‘HashRouter’:uses the Has portion of the URL(window.location.hash)to keep the UI in sync with the URL.

  • ‘memoryRouter’:Keeps the history of the URL in the memory(does not read or write to the address bar).

  1. Link: the link component is used to create navigational links.It is similar to anchor (‘<a>’) tag but prevents the browser from refreshing the page.

  2. Switch: the switch component is used to render only the first ‘Router’ that matches the current location.it is useful for defining or “catch-all” route

  3. Dynamic Routing: you can create dynamic routes that match any path using parameters.Parameters are specific with a colon (:) in the path

Advanced Features

  1. Nested Routes:you can define routes with other components,allowing for nested routing structures

  2. Redirects: the redirects component is used to navigate programmatically

  3. Programmatic Navigation: you can navigate programmatically using the ‘history’ object provided by React Router

  4. Custom Route Matching: you can use the ‘matchPath’ function to perform custom matching logic

React Router Hooks

React Router also provide hooks to work with routing in function components

  1. useHistory:Gives acesse to the ‘history’ instance

  2. useLocation: Provides the current location object

  3. useParam: returns the matched params

  4. useRouteMatch:provides match information

React Router is a powerful and flexible routing solution for react applications making it easy to manage navigation and URLs in a declarative manner.