How to use the React-Router useHistory hook for navigation



Image not found!!

The useHistory hook is part of the react-router-dom library and is used to manage navigation history in a React application using React Router. It provides access to the history object, which allows you to programmatically navigate to different pages in your application.

Here's a basic example of how to use the useHistory hook:

  1. Install react-router-dom if you haven't already:
bash
npm install react-router-dom
  1. Import the necessary components and hooks in your React component file:
jsx
import React from 'react'; import { useHistory } from 'react-router-dom';
  1. Use the useHistory hook in your component:
jsx
function MyComponent() { const history = useHistory(); const handleButtonClick = () => { // Use the push method to navigate to a new route history.push('/new-route'); }; return ( <div> <h1>My Component</h1> <button onClick={handleButtonClick}>Go to New Route</button> </div> ); } export default MyComponent;

In this example, when the button is clicked, the handleButtonClick function is called, which uses the history.push method to navigate to the '/new-route'. The useHistory hook gives you access to the history object, which includes methods like push, replace, go, etc.

You can also use the useHistory hook to go back or forward in the history stack:

jsx
const handleGoBack = () => { // Go back one step in the history stack history.goBack(); }; const handleGoForward = () => { // Go forward one step in the history stack history.goForward(); };

Remember to wrap your component with a BrowserRouter or another appropriate router from react-router-dom in a higher-level component in your application:

jsx
import { BrowserRouter as Router } from 'react-router-dom'; function App() { return ( <Router> <MyComponent /> {/* Other components and routes go here */} </Router> ); }

This ensures that the useHistory hook has access to the router context.