Answer the question
In order to leave comments, you need to log in
Why doesn't Redirect react-router-dom work?
Hello! Faced a small problem.
import React, {useState, useEffect} from 'react';
import Navbar from './Navbar';
import {connect} from 'react-redux';
import Auth from './Auth';
import MainPage from './MainPage';
import { CSSTransition } from 'react-transition-group';
import {Route, Redirect, Switch, withRouter} from 'react-router-dom';
function App(props) {
const [animation, showAnimation] = useState(false);
useEffect(() => {
showAnimation(true);
})
console.log(props.isLogin); // выводит правильно
return (
<div className="d-flex flex-column flex-fill h-100">
<Navbar />
<Switch>
<Route path='/auth' render={() =>
<CSSTransition
in={animation}
timeout={500}
classNames="login"
unmountOnExit
>
<Auth />
</CSSTransition>
} />
<Route path='/main' component={MainPage} />
{props.isLogin ? <Redirect to="/main" /> : <Redirect to="/auth" />}
</Switch>
</div>
);
}
export default withRouter(connect(
state => ({
isLogin: state.login.isLogin
}),
null
)(App));
Answer the question
In order to leave comments, you need to log in
it will only redirect you if you are not on / main or / auth, otherwise the first two Routes in Switch will work and Redirect will simply not reach.
you can add a props.isLogin check to each Route
{props.isLogin && }
{!props.isLogin && }
but that's not accurate
https://reacttraining.com/react-router/web/example... see more as an example.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question