Table of contents
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
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.
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).
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.
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
Dynamic Routing: you can create dynamic routes that match any path using parameters.Parameters are specific with a colon (:) in the path
Advanced Features
Nested Routes:you can define routes with other components,allowing for nested routing structures
Redirects: the redirects component is used to navigate programmatically
Programmatic Navigation: you can navigate programmatically using the ‘history’ object provided by React Router
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
useHistory:Gives acesse to the ‘history’ instance
useLocation: Provides the current location object
useParam: returns the matched params
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.