React-router dom
INTRODUCTION
React-router dom is a both client-based and server-side routing that is majorly used by single-page applications i.e. applications that have many pages or components but the page is never refreshed instead the content is dynamically fetched based on the URL from a link click without making another request for another document from the server.
VERSIONS
Commonly used react-router dom versions are v5 and v6
React Router V5
To install v5 of react-router dom using npm or yarn packet manager using the following commands in your project.
for npm use npm i react-router-dom@5.2.0 Version
Package version 5.2.3 doesn’t exist.
for yarn use yarn add react-router-dom@5
React Router DOM v5 introduces a few new features and improvements over the previous version, including support for React Hooks and improved support for server-side rendering.
Here are some of the most commonly used props in React Router DOM v5:
BrowserRouter
- A router that uses HTML5 history API to keep the UI in sync with the URL. It provides thehistory
object to child components through thecontext
API.
import { BrowserRouter} from 'react-router-dom';
function App() {
return (
<BrowserRouter>
</BrowserRouter>
);
}
Route
- A component that renders some UI when the location matches its path. It has props likepath
(the URL pattern to match),exact
(whether or not to match the URL exactly), andcomponent
(the component to render).
import { BrowserRouter, Route,} from 'react-router-dom';
function App() {
return (
<BrowserRouter>
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
<Route path="/contact" component={Contact} />
<Route component={NotFound} />
</BrowserRouter>
);
}
Switch
- A component that renders the first childRoute
orRedirect
that matches the location. It should contain onlyRoute
orRedirect
components as its children.
import { BrowserRouter, Route, Switch } from 'react-router-dom';
function App() {
return (
<BrowserRouter>
<Switch>
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
<Route path="/contact" component={Contact} />
<Route component={NotFound} />
</Switch>
</BrowserRouter>
);
}
Link
- A component that renders an anchor tag with anhref
that corresponds to the givento
prop. It provides a way to navigate between pages without triggering a full refresh.
import { Link } from 'react-router-dom';
function Navbar() {
return (
<nav>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/about">About</Link>
</li>
<li>
<Link to="/contact">Contact</Link>
</li>
</ul>
</nav>
);
}
You can also use the NavLink
component instead of Link
if you want to add additional styling or functionality to your links, like adding an active class for the current route.
Redirect
- A component that redirects to a new location. It has ato
prop that specifies the new location and can be used inside aSwitch
component to redirect to a default route if no other routes match.
import { Redirect, Route, Switch } from 'react-router-dom';
function App() {
return (
<Switch>
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
<Route path="/contact" component={Contact} />
<Redirect to="/" />
</Switch>
);
}
useHistory
- A React Hook that provides access to thehistory
object from within a component.
import { useHistory } from 'react-router-dom';
function Login() {
const history = useHistory();
const handleLogin = () => {
// Perform login logic here
// …
// Redirect to the home page
history.push('/');
};
return (
<div>
<h1>Login</h1>
<button onClick={handleLogin}>Log In</button>
</div>
);
}
useParams
- A React Hook that provides access to the dynamic segments of the current URL. It is used inside aRoute
component that has dynamic segments in itspath
prop.
import { useParams } from 'react-router-dom';
function UserProfile() {
const { username } = useParams();
return (
<div>
<h1>User Profile: {username}</h1>
{/* Render user profile details here */}
</div>
);
}
React Router V6
React-router dom v6 is the latest mind-blowing version of the dom with many changes made from the previous version v5. we’re going to look at the various changes but first, we need to install the V6 version in our project.
To install React Router, all you have to do is run npm install react-router-dom@6 in your project terminal and then wait for the installation to complete.
If you are using yarn then use this command: yarn add react-router-dom@6
- Bundle Size: React Router v6 has made improvements to the bundle size by splitting the package into smaller chunks, resulting in a smaller overall bundle size compared to v5. This can lead to faster loading times for your application.
2. Nested Routes: In React Router v6, nested routes are handled using the Outlet
component. The Outlet
component acts as a placeholder for nested routes and renders the appropriate child route components based on the URL. Here's an example:
In React Router v5:
<Route path="/about" component={About}>
<Route path="/about/team" component={Team} />
<Route path="/about/history" component={History} />
</Route>
In React Router v6:
<Route path="/about">
<About />
<Route index path="/team" element={<Team />} />
<Route index path="/history" element={<History />} />
</Route>
In v6, nested routes are defined using the element
prop instead of the component
prop. The index
prop is used to specify the default child route to be rendered when the parent route is matched.
3. Switch
to Routes
: In React Router v6, the Switch
component from v5 has been replaced with the Routes
component. The Routes
component provides a more declarative way of defining routes and handling route matching. Here's an example:
In React Router v5:
<Switch>
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
<Route path="/contact" component={Contact} />
</Switch>
In React Router v6:
<Routes>
<Route index path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/contact" element={<Contact />} />
</Routes>
In v6, routes are defined as children of the Routes
component using the element
prop instead of the component
prop, and the index
prop is used to specify the default route to be rendered when no other routes match.
4. useNavigate
instead of useHistory
: In React Router v6, the useHistory
hook has been replaced with the useNavigate
hook for handling navigation. The useNavigate
hook provides a more concise and intuitive way of handling navigation actions in your components. Here's an example:
In React Router v5:
import { useHistory } from 'react-router-dom';
const MyComponent = () => {
const history = useHistory();
const handleButtonClick = () => {
history.push('/about');
}
return (
<button onClick={handleButtonClick}>Go to About</button>
);
}
In React Router v6:
import { useNavigate } from 'react-router-dom';
const MyComponent = () => {
const navigate = useNavigate();
const handleButtonClick = () => {
navigate('/about');
}
return (
<button onClick={handleButtonClick}>Go to About</button>
);
}
In v6, the useNavigate
hook is used to handle navigation actions instead of the useHistory
hook, providing a more intuitive and concise way of handling navigation in your components.