React Router
What is React Router?
React Router is a library for managing navigation and routing in React applications. It allows developers to define routes that map URL paths to specific components, enabling navigation between different pages or views within a single-page application (SPA). React Router makes it easy to build dynamic and interactive applications with client-side routing.
How do you install React Router?
To use React Router in your project, you need to install the react-router-dom
package. You can install it using npm or yarn:
npm install react-router-dom
yarn add react-router-dom
After installing, you can import the necessary components, such as BrowserRouter
, Routes
, Route
, and others, into your React application.
What are the key components of React Router?
The key components of React Router include:
BrowserRouter
: The router component that wraps your application. It listens to the browser's URL and renders the corresponding components based on the defined routes.Routes
: A wrapper component that houses all the route definitions. Inside it, you define individualRoute
components.Route
: A component that defines a path and the corresponding component to render when the URL matches that path.Link
: A component that provides navigation between routes without reloading the page, similar to an anchor tag but for client-side routing.NavLink
: A specialized version ofLink
that allows for styling the active link based on the current route.useNavigate
: A hook used to programmatically navigate between routes.
How do you set up routing in a React application?
To set up routing in a React application, you need to wrap your app with BrowserRouter
and define your routes using Routes
and Route
components.
Example of setting up routing:
import React from 'react';
import { BrowserRouter as Router, Routes, Route, Link } from 'react-router-dom';
function Home() {
return <h1>Home Page</h1>;
}
function About() {
return <h1>About Page</h1>;
}
function App() {
return (
<Router>
<nav>
<Link to="/">Home</Link> |
<Link to="/about">About</Link>
</nav>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
</Router>
);
}
export default App;
In this example, Router
wraps the entire application, and Routes
defines the paths /
and /about
, which render the Home
and About
components respectively.
What is the difference between Link
and NavLink
?
Link
and NavLink
are both components used to navigate between routes, but they have some key differences:
Link
: Provides navigation between routes without reloading the page. It works similarly to the HTML anchor tag but for client-side routing.NavLink
: ExtendsLink
and adds styling capabilities to the active link. It allows you to apply a specific class or style to the currently active link based on the current URL.
Example of using NavLink
:
import { NavLink } from 'react-router-dom';
function Navbar() {
return (
<nav>
<NavLink to="/" activeClassName="active">Home</NavLink>
<NavLink to="/about" activeClassName="active">About</NavLink>
</nav>
);
}
In this example, the NavLink
component applies the active
class to the link that corresponds to the current URL.
What is the useNavigate
hook?
useNavigate
is a hook in React Router that allows you to programmatically navigate to different routes. It is especially useful when you need to navigate based on user actions, such as submitting a form or clicking a button.
Example of using useNavigate
:
import React from 'react';
import { useNavigate } from 'react-router-dom';
function Contact() {
const navigate = useNavigate();
const handleSubmit = () => {
// After form submission, navigate to the Home page
navigate('/');
};
return (
<div>
<h1>Contact Page</h1>
<button onClick={handleSubmit}>Submit</button>
</div>
);
}
export default Contact;
In this example, useNavigate
is used to navigate to the /
route after the form is submitted.
What is the useParams
hook?
The useParams
hook is used to access URL parameters in React Router. It returns an object containing key-value pairs of the dynamic segments of the URL (e.g., /user/:id
).
Example of using useParams
:
import React from 'react';
import { useParams } from 'react-router-dom';
function UserProfile() {
const { id } = useParams(); // Access the URL parameter `id`
return <h1>User ID: {id}</h1>;
}
export default UserProfile;
In this example, if the URL is /user/123
, the id
will be 123
, and the UserProfile
component will display "User ID: 123".
How do you handle 404 pages in React Router?
To handle 404 pages (routes that do not match any defined routes), you can define a fallback Route
at the end of your Routes
list with a path that matches everything using the *
wildcard.
Example of handling 404 pages:
function NotFound() {
return <h1>404 - Page Not Found</h1>;
}
function App() {
return (
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="*" element={<NotFound />} /> {/* Catch-all route for 404 */}
</Routes>
);
}
In this example, the NotFound
component is rendered for any route that does not match the defined routes, providing a 404 page.
How do you create nested routes in React Router?
Nested routes allow you to define child routes inside parent routes. This is useful when you want to create layouts that have shared components, such as a header or sidebar, while also rendering different content based on the route.
Example of nested routes:
import { BrowserRouter as Router, Routes, Route, Link } from 'react-router-dom';
function Dashboard() {
return (
<div>
<nav>
<Link to="profile">Profile</Link> |
<Link to="settings">Settings</Link>
</nav>
<Routes>
<Route path="profile" element={<Profile />} />
<Route path="settings" element={<Settings />} />
</Routes>
</div>
);
}
function App() {
return (
<Router>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/dashboard/*" element={<Dashboard />} />
</Routes>
</Router>
);
}
In this example, Dashboard
contains nested routes for Profile
and Settings
. When the user navigates to /dashboard/profile
or /dashboard/settings
, the appropriate nested component is rendered.
What is useLocation
in React Router?
useLocation
is a hook that returns the current location object, which contains information about the current URL. It provides details such as the pathname, search parameters, and hash. This is useful for components that need to react to URL changes or display information based on the current route.
Example of using useLocation
:
import { useLocation } from 'react-router-dom';
function LocationInfo() {
const location = useLocation();
return (
<div>
<p>Current Path: {location.pathname}</p>
<p>Search Params: {location.search}</p>
</div>
);
}
In this example, useLocation
is used to display the current URL path and any search parameters.