How to redirect a page to menu on reload or refresh page with react?

I want to redirect a user to the menu page when he reload or refersh the current page.

Menu.js:

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

export default function Menu() {
  const history = useHistory();
  const handleClick = () => {
    history.push("/myComponent");
  };
  return (
    <div>
      <h1>Menu Page</h1>
      <button onClick={handleClick}>Go to MyComponent</button>
    </div>
  );
}

MyComponent.js:

import React, { useEffect } from "react";
import { useHistory } from "react-router-dom";

export default function MyComponent() {
  const history = useHistory();
  const handler = function () {
    history.push("/");
  };
  useEffect(() => {
    window.addEventListener("beforeunload", handler);
    return () => {
      window.removeEventListener("beforeunload", handler);
    };
  }, []);
  return (
    <div>
      <h1>My Component Page</h1>
    </div>
  );
}

App.js:

import { Router, Route } from "react-router-dom";
import Menu from "./Menu";
import MyComponent from "./MyComponent";
import { createBrowserHistory } from "history";

const history = createBrowserHistory();

export default function App() {
  return (
    <Router history={history}>
      <Route exact path="/" component={Menu} />
      <Route exact path="/myComponent" component={MyComponent} />
    </Router>
  );
}

When I’m on MyComponent page and I reload the page the path url changed to ‘/’ but the page displayes the content of MyComponent.
I want to be redirected only to Menu only when I refresh the page or reload it by click on reload page button on the browser. How can I fix that?

1 thought on “How to redirect a page to menu on reload or refresh page with react?”

  1. You need to add switch:

    <Router history={history}>
        <Switch>
          <Route exact path="/" component={Menu} />
          <Route exact path="/myComponent" component={MyComponent} />
        </Switch>
      </Router>
    
    Reply

Leave a Comment