Sarath KrishnanFeb. 10, 2025
Efficient navigation is a key component of any web application, and React Router makes it simple. In this step-by-step guide, we’ll explore how to set up a React Router, define routes, and navigate smoothly within a React app.
To get started, install React Router using npm:
npm install react-router-dom
Wrap your application with <BrowserRouter> and define routes using <Routes> and <Route> components:
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import Home from './Home';
import About from './About';
function App() {
return (
<Router>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
</Router>
);
}
export default App;
Use the <Link> component instead of <a> tags to ensure smooth navigation without reloading the page:
import { Link } from 'react-router-dom';
function Navbar() {
return (
<nav>
<Link to="/">Home</Link>
<Link to="/about">About</Link>
</nav>
);
}
Use the useNavigate hook to navigate programmatically within your application:
import { useNavigate } from 'react-router-dom';
function Dashboard() {
const navigate = useNavigate();
const goToProfile = () => {
navigate('/profile');
};
return <button onClick={goToProfile}>Go to Profile</button>;
}
React Router allows dynamic parameters in URLs. Define a route with a dynamic segment:
<Route path="/user/:id" element={<UserProfile />} />
Retrieve the parameter using the useParams hook:
import { useParams } from 'react-router-dom';
function UserProfile() {
const { id } = useParams();
return <h1>User ID: {id}</h1>;
}
Nested routes help create structured layouts with shared components:
<Route path="/dashboard" element={<Dashboard />}>
<Route path="profile" element={<Profile />} />
</Route>
By following this step-by-step guide, you can easily set up React Router for smooth navigation in your React applications. With tools like <Link>, useNavigate, and dynamic routes, you can create a smooth and efficient user experience.
Start integrating React Router today and enhance your app’s navigation!
1