Yasin Yaqoobi
Yasin Yaqoobi

Reputation: 2040

hashRouter push history regular route

I am using react-router "5.3.3" and not sure how to navigate out of a hash router once I am inside it. i.e.

I have

<BrowserRouter>
  <Route path="/profile">
    <profilePage />
  </Route>
  <HashRouter>
    <FormComponents>
  </HashRouter>
</BrowserRouter>

This is a multistep form and the initial URL is something like example.com/form and on every stage i.e. when you add email and hit submit it will change the browser URL to example.com/form#password but on the last submission which is the verification step, I want to route to example.com/profile. using the default const history = useHistory(); history.push("/profile"); will just change the URL to example.com/form/#profile.

I tried using the default browser history object history.pushState({}, "Profile", "/profile"); It navigates to the correct URL, but the app doesn't re-render.

Upvotes: 1

Views: 1771

Answers (1)

Drew Reese
Drew Reese

Reputation: 202846

One thought might be to create a global history object the main/outer router uses (i.e. createBrowserHistory) and import and use that history object to issue the navigation action from within the inner router. The idea is to use the history object of the relevant router/routing context.

Example:

import {
  Router,
  HashRouter,
  Route,
  Link,
  Redirect,
  useRouteMatch
} from "react-router-dom";
import { createBrowserHistory } from "history"; // v4

const browserHistory = createBrowserHistory();

const ProfilePage = () => (
  <>
    <h1>ProfilePage</h1>
    <ul>
      <li>
        <Link to="/form">Enter Form</Link>
      </li>
    </ul>
  </>
);

const FormComponents = () => {
  const { url } = useRouteMatch();

  const navigateToProfile = (e) => {
    e.preventDefault();
    browserHistory.push("/profile");
  };

  return (
    <>
      <h1>FormComponents</h1>
      <ul>
        <li>
          <Link to={`${url}step1`}>Step 1</Link>
        </li>
        <li>
          <Link to={`${url}step2`}>Step 2</Link>
        </li>
        <li>
          <Link to={`${url}step3`}>Step 3</Link>
        </li>
        <li>
          <Link onClick={navigateToProfile} to="/profile">
            Profile
          </Link>
        </li>
      </ul>
    </>
  );
};

export default function App() {
  return (
    <div className="App">
      <Router history={browserHistory}>
        <Route path="/profile">
          <ProfilePage />
        </Route>
        <Route path="/form">
          <HashRouter>
            <FormComponents />
          </HashRouter>
        </Route>
        <Redirect to="/profile" />
      </Router>
    </div>
  );
}

Edit react-router-hashrouter-push-history-regular-route

Upvotes: 1

Related Questions