React Router not routing correctly after sign in

Viewed 36
function Login() {
    const history = useHistory();
    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');

    const signIn = e => {
        e.preventDefault();

        auth
            .signInWithEmailAndPassword(email, password)
            .then(auth => {
                history.push('/home')
            })
            .catch(error => alert(error.message))
    }

    const register = e => {
        e.preventDefault();

        auth
            .createUserWithEmailAndPassword(email, password)
            .then((auth) => {
                // it successfully created a new user with email and password
                if (auth) {
                    history.push('/home')
                }
            })
            .catch(error => alert(error.message))
    }

    return (
        <div className='login'>
            <Link to='/'>
                <img
                    className="login__logo"
                     src='' />
            </Link>

            <div className='login__container'>
                <h1>Ticket System</h1>

                <form>
                    <h5>E-mail</h5>
                    <input type='text' value={email} onChange={e => setEmail(e.target.value)} />

                    <h5>Password</h5>
                    <input type='password' value={password} onChange={e => setPassword(e.target.value)} />

                    <button type='submit' onClick={signIn} className='login__signInButton'>Sign In</button>
                </form>

                <p>
                
                </p>

                <button onClick={register} className='login__registerButton'>Register Your Account</button>
            </div>
        </div>
    )
}


function App() {

  return (
    <Router>
      <div className="app">
      <Login />
        <Switch>

        <Route path="/">
            <Login />
          </Route>
          <Route path="/home">
            <Home />
          </Route>

        </Switch>
      </div>
    </Router>
  );
}

import React from "react";


function Home() {
  return (
    <div className="home">
        <h1>hello world</h1>
  
    </div>
  );
}

export default Home;

These are the app, home, login js files when I sign in it does not route to home not sure what is going on. I am trying to go to "/home" after I click sign in, the account I am using is registered. On sign in the route url does change to /home but does not go to the contents in it just stays on the login page

1 Answers

when your project runs in a browser, the router finds a specific path so you should add exact in one path.

function App() {

  return (
    <Router>
      <div className="app">
      <Login />
        <Switch>

        <Route path="/">
            <Login />
          </Route>
          <Route exact path="/home">
            <Home />
          </Route>

        </Switch>
      </div>
    </Router>
  );
}
Related