@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:
- Install React Router using the following command:
1
|
npm install react-router-dom
|
- Import the necessary components from React Router in your login component file:
1
|
import { useHistory } from 'react-router-dom';
|
- In your login component, initialize the useHistory hook:
1
|
const history = useHistory();
|
- 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');
|
- 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;
|
- 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.