Home > Enterprise >  Use Navigation not popping back route, if I press the button more than one time
Use Navigation not popping back route, if I press the button more than one time

Time:02-02

This is app js code I use nav bar and Routes


export default function App() {

    return (
        
    <main>
        <Navbar />

        <Routes>
        <Route path="/" element={<Username/>}/>
        <Route path="/register" element={<Register/>}/>
       
      </Routes>
      </main>

    )
  }

This is button component

import React from "react";
import { useNavigate } from "react-router-dom";

export const Button = () => {
  const navigate = useNavigate({ replace: true });

  return (
    <>
      <button
        onClick={() => navigate("../register")}
        className='justify-center items-center bg-buttoncolor text-white px-6 py-2 rounded-full'
      >
        Sign Up Now
      </button>
    </>
  );
};

export default Button;

When I press this button twice or more than one and after that I click back button (Browser back button) I must click the back button same time to go back to previous route e.g if I press button 10 times then I have to press back 10 time to go back to previous route

CodePudding user response:

This issue is happening because the useNavigate hook with the replace option set to true is replacing the current route in the history instead of adding a new one. This makes the browser's back button go back to the previous route only after it has removed all of the replaced routes.

To resolve this issue, you can change the replace option to false, which will add a new route to the history instead of replacing the current one. The code would look like this:

const navigate = useNavigate({ replace: false });

CodePudding user response:

import React from "react";
import { useNavigate ,useLocation } from "react-router-dom";

export const Button = () => {
  const navigate = useNavigate();
  const location = useLocation();

  return (
    <>
      <button
      
        onClick={() => {
          (location.pathname === "/register") ? [] = [] :navigate("../register")
          
      
      }}
        className="justify-center items-center bg-buttoncolor text-white px-6 py-2 rounded-full"
      >
        Sign Up Now
      </button>
    </>
  );
};

export default Button;

According to the question (if I press the button more than one times then i have to press back button more than one times to go back to previous route) The answer to this question is that we can check the route by

useLocation() (location.pathname === "/register") ? [] = [] :navigate("../register")

if the route is same we will remain on the same route even we press the button as many times we want and when press back browser button we can go back to previous route.

  • Related