How to use the useNavigate hook In ReactJS
In this approach, we are using the useNavigate hook to programmatically navigate. This hook provides a navigation function that allows us to navigate to a different route within the application.
Syntax:
const navigate = useNavigate();
navigate('path-name');
Example: Below is the implementation for above approach.
// App.js
import React from 'react';
import { Route, Routes } from 'react-router-dom';
import { BrowserRouter } from 'react-router-dom'
import MyComponent from './components/MyComponent';
import Profile from './components/Profile';
const App = () => {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<MyComponent />} />
<Route path="/profile" element={<Profile />} />
</Routes>
</BrowserRouter>
);
};
export default App;
// components/MyComponent.js
import React from 'react';
import { useNavigate } from 'react-router-dom';
function MyComponent() {
const navigate = useNavigate();
function handleClick() {
navigate('/profile');
}
return (
<>
<h1>Welcome to w3wiki</h1>
<button onClick={handleClick}>Go to profile</button>
</>
);
}
export default MyComponent;
// components/Profile.js
import React from 'react';
const Profile = () => {
return (
<>
<h1>Welcome to Your Profile</h1>
<p>This is your profile page.
You can view and edit your profile information here.
</p>
</>
);
};
export default Profile;
Output:
How to programmatically navigate using React Router ?
React Router provides a way to navigate between different parts of an application when certain events occur, such as button clicks or form submissions. Programmatically navigating allows us to change the URL of an application without a full page reload, enabling a smoother user experience.
We will discuss the different approaches to navigating using React Router:
Table of Content
- Using the useNavigate hook
- Using the Link Component