Reputation: 3
I'm trying to redirect from a login screen to a home screen. How do I implement a conditional redirect correctly in ReactJS?
I have tried to redirect to components based on the state. this.state.loggedIn returns true or false as I expect it to do.
import React from 'react';
import {Router,
Route,
Link,
Redirect
} from "react-router-dom";
import history from '../history';
import LoginView from './LoginView';
import SearchPanel from './SearchPanel';
import "./style.css";
class App extends React.Component {
state = { token: '', groupId: '', hostName: '', loggedIn: false};
getLoginData = async (props) => {
this.setState({loggedIn: true});
console.log(this.state.loggedIn);
this.setState({ token: props.token, groupId: props.token.groupId.data, hostName: props.token.hostName} );
};
render() {
return (
<Router history={history}>
<div className="background">
<Route
exact
path="/"
render={() =>
!this.state.loggedIn ? (
history.replace("/login")
) : (
history.replace("/home")
)
}
/>
<Route
path="/login"
component={() => <LoginView onLogin={this.getLoginData} />}
/>
<Route
path="/home"
component={() => (
<SearchPanel
token={this.state.token}
groupId={this.state.groupId}
hostName={this.state.hostName}
/>
)}
/>
</div>
</Router>
)
}
}
export default App;
I expect to be redirected to /home, but it stays on /login
Upvotes: 0
Views: 2418
Reputation: 1183
I needed to do this today. Here's my code, mind i decided to make this a HOC that you can choose to wrap or not wrap. For use cases that have multiple redirect cases you'll definitely want to use this inline instead of as a wrapper.
import React from 'react';
import {Redirect} from 'react-router';
interface IConditionalRedirectProps {
shouldRedirect: boolean,
to: string
}
export const ConditionalRedirect: React.FC<IConditionalRedirectProps> = (props) => {
const {shouldRedirect, to, children} = props;
if (shouldRedirect) {
console.log('redirecting');
return <Redirect to={to}/>
} else {
return (
<>
{children}
</>
)
}
};
Usage:
<ConditionalRedirect shouldRedirect={someFunctionThatReturnsBool()}
to={'some url'}>
<Normal Elements here>
</ConditionalRedirect>
Upvotes: 0
Reputation: 1811
<Route/>
has an history object, use that
this.props.history.replace("/home")
Using .replace()
assures that the user can't navigate back to login again. Otherwise use .push()
.
Upvotes: 1