Home > database >  When the login button is clicked, the url is changed, but it does not go to the login page
When the login button is clicked, the url is changed, but it does not go to the login page

Time:03-22

//App.tsx

function App() {
  return (
    <BrowserRouter>
      <Router />
    </BrowserRouter>
  );
}

export default App;
//Router.tsx

const Router = () => {
  return (
    <BrowserRouter>
      <div className="App">
        <Switch>
          <Route exact path="/login">
            <Login />
          </Route>
          <Route exact path="/signup">
            <SignUp />
          </Route>
        </Switch>
      </div>
    </BrowserRouter>
  );
};

export default Router;

This image is Login Page enter image description here

When I clicked the Login Link in App.tsx, Login Page

URL was changed to /login, but I have to refresh for it to take effect. just see empty page..

I want to show the login page right away when I click the login link.

CodePudding user response:

React router is not recognizing the state change because it only takes place in the child component (Router.tsx).

Move all the JSX from Router.tsx into the main App.tsx file. This should fix your problem.

CodePudding user response:

From react-router docs You should never have more then one BrowserRouter component you used this multiple times this whats cause your error.

Your App component required to warped inside BrowserRouter at App.tsx file only ones.

//App.tsx

function App() {
  return (
    <BrowserRouter>
      <Router />
    </BrowserRouter>
  );
}

export default App;

change your Router.tsx file by flowing way

//Router.tsx
    const Router = () => {
      return (
          <div className="App">
            <Switch>
              <Route exact path="/login">
                <Login />
              </Route>
              <Route exact path="/signup">
                <SignUp />
              </Route>
            </Switch>
          </div>
      );
    };
    
    export default Router;
  • Related