0

In my react app I have /lead-manager route, /login route and there is / route, latter which is the app.js itself that I don't want anyone to access, if someone just goes to the / route I wanted them to redirect to /lead-manager route. So this is what I did according to the solution given here.

My app.jsx part

import {
  BrowserRouter as Switch,
  useHistory,
  Route,
  useLocation,
} from "react-router-dom";

const App = ({ confirmAuthentication }) => {
  let location = useLocation();
  let history = useHistory();

  useEffect(() => {
    async function fetchIt() {
      if (localStorage.jwt !== undefined) {
        confirmAuthentication();
      }
    }
    fetchIt();
    if (location.pathname === "/") {
      history.push("lead-manager");
    }
  }, []);
 return (
    <div>
      <Switch>
        <Route exact path="/testing">
          <TestingComponent />
        </Route>
        <PrivateRoute path="/lead-manager" component={LeadApp} />
        <Route exact path="/login">
          <LoginView />
        </Route>
      </Switch>
    </div>
  );
}

The output I'm getting when I'm accessing / path is /lead-manager in the URL. Which is the desired one, but the component doesn't render accordingly with components defined in /lead-manager route. It just stays on / route even though URL shows /lead-manager

Hope this is clear

Faiz Hameed
  • 488
  • 7
  • 15

1 Answers1

1

In order to use history correctly you need to have a Router wrapping App component up in the hierarchy. Since you are rendering Router within App component, it isn't able to listen to the history changes since the history provided by useHistory doesn't refer to the history used by Router unless App component is wrapped by Router.

Do not render Router inside of App component

Also you have rendered Router as the Switch component inside App component, you must instead import the exact Switch component from react-router-dom

Check updated code below

import {


    BrowserRouter as Router,
      Switch
      useHistory,
      Route,
      useLocation,
    } from "react-router-dom";

    const App = ({ confirmAuthentication }) => {
      let location = useLocation();
      let history = useHistory();

      useEffect(() => {
        async function fetchIt() {
          if (localStorage.jwt !== undefined) {
            confirmAuthentication();
          }
        }
        fetchIt();
        if (location.pathname === "/") {
          history.push("lead-manager");
        }
      }, []);
     return (
        <div>
          <Switch>
            <Route exact path="/testing">
              <TestingComponent />
            </Route>
            <PrivateRoute path="/lead-manager" component={LeadApp} />
            <Route exact path="/login">
              <LoginView />
            </Route>
          </Switch>
        </div>
      );
    }

    export default (props) => <Router><App {...props}/></Router>  
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400