In React, you can navigate to the previous page using the useNavigate hook from React Router v6. The useNavigate hook provides a navigate function that allows you to programmatically navigate. To go back to the previous page, you can pass -1 as an argument to the navigate function.
Steps:
Import useNavigate from react-router-dom.
Call useNavigate to get the navigate function.
Use navigate(-1) to go back to the previous page.
Example Code:
import React from 'react';
import { useNavigate } from 'react-router-dom';
function BackButton() {
const navigate = useNavigate();
const goBack = () => {
navigate(-1); // Navigates to the previous page
};
return (
<button onClick={goBack}>Go Back</button>
);
}
export default BackButton;