Programmatic navigation in React can be done using the useNavigate
hook from React Router v6 or higher. This allows you to navigate to different routes in your application without relying on anchor tags or link components.
Here’s an example of how to use programmatic navigation:
- Install React Router if you haven’t already:
npm install react-router-dom
-
Set up Routes in your app (e.g.,
App.js
):
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
useNavigate
hook for programmatic navigation inside a component:
import { useNavigate } from 'react-router-dom';
function Home() {
const navigate = useNavigate();
const handleClick = () => {
// Navigate to the About page
navigate('/about');
};
return (
<div>
<h1>Home Page</h1>
<button onClick={handleClick}>Go to About Page</button>
</div>
);
}
export default Home;
Explanation:
- The
useNavigate
hook is used to create anavigate
function, which can be called to move to a different route. - You can pass the path to
navigate()
as a string (e.g.,/about
) to navigate to that route. - Optionally, you can pass a second argument with options, such as
replace: true
to replace the current entry in the history stack (instead of adding a new one).
This is a clean and easy way to control navigation programmatically in a React application.
Top comments (0)