In a React application, you can navigate to the previous page using the useHistory hook from the react-router-dom library. This library provides tools for managing routing within a React application. Here’s how you can use it to go back to the previous page:
Install the react-router-dom package if you haven’t already:
npm install react-router-dom
In your React component, import the necessary components and use the useHistory hook:
import React from 'react';
import { useHistory } from 'react-router-dom';
function MyComponent() {
const history = useHistory();
const goBack = () => {
history.goBack(); // Go back to the previous page
};
return (
<div>
<p>This is my component.</p>
<button onClick={goBack}>Go Back</button>
</div>
);
}
export default MyComponent;
In this example, the useHistory hook from react-router-dom is used to access the browser’s navigation history. The goBack function is called when the button is clicked, which triggers the history.goBack() method and navigates the user to the previous page in the history stack.
Make sure your component is wrapped within a Router component from react-router-dom for this to work properly.
