How to redirect after logging in to React.js?

Member

by jerad , in category: Javascript , 6 months ago

How to redirect after logging in to React.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by kadin , 6 months ago

@jerad 

To redirect after logging in to React.js, you can make use of the React Router library. Here's a step-by-step guide on how to achieve this:

  1. Install React Router using the following command:
1
npm install react-router-dom


  1. Import the necessary components from React Router in your login component file:
1
import { useHistory } from 'react-router-dom';


  1. In your login component, initialize the useHistory hook:
1
const history = useHistory();


  1. After the user successfully logs in, use the history.push() method to redirect them to the desired route. For example, if you want to redirect to a homepage route, you can do the following:
1
history.push('/homepage');


  1. In your main component file (usually the one where you define your routes), import the necessary components from React Router and define your routes. For example:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import Homepage from './Homepage';
import Login from './Login';

function App() {
  return (
    <Router>
      <Switch>
        <Route exact path="/" component={Login} />
        <Route exact path="/homepage" component={Homepage} />
      </Switch>
    </Router>
  );
}

export default App;


  1. Now, when the user logs in, they will be redirected to the "/homepage" route.


Ensure that you have defined the React Router component hierarchy correctly for the routing to work appropriately.