Home > Software engineering >  How do I redirect after login to another page in ReactJs [closed]
How do I redirect after login to another page in ReactJs [closed]

Time:09-30

I am new to react js and wondering how i can redirect to another pages when a client is logged in {user ? (Redirect exact path="/Study")

CodePudding user response:

If you are using React Router you can do something like

const [user, setUser] = useState(null);
const history = useHistory();
useEffect(()=>{
  if(user){
    history.push('/otherRoute');
  }
}, [user])

and then just setUser to the user when you handle the login, or do something like

  <Route
    render={() => (!user ? <Something/> : <Redirect to="/Study" />)}
  />

CodePudding user response:

Question is quite broad and is a bit difficult to answer correctly. It depends a bit if you are using some routing-library or not. Then you might have different routing recommendations made available by your selected router.

But if we assume we do not have any router-library and just want to have some state and when it changes we change our url to something different we could approach it as follows.

Full working example(Codesandbox Link)

import { memo, useEffect, useState } from "react";

export default function App() {
  // State to save current user, default to "undefined"
  const [user, setUser] = useState();

  // Inline Login-button component
  const Login = memo(() => (
    <button onClick={() => setUser({ username: "user1" })}>Sign in</button>
  ));

  // In use effect we listen any changes to User-state object with dependency array
  useEffect(() => {
    // On initial render user does not exist return early
    if (!user) return;
    // If user exists we push new browser history-state. You might want to have more specific check if certain key/value exists.
    // args (state, title, route)
    window.history.pushState(null, "Redirected Page", "/new_page");
    // Artificial page-reload to update window.location-object
    window.location.reload();
  }, [user]);

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <Login />
      <a href="/">Frontpage</a>
    </div>
  );
}


You can follow same pattern but use your router-library route/redirection -function as stated in the documentation.

  • Related