24

Brand new to react, Attempting to redirect to a "homepage" after clicking submit on a "login" page. Tried to follow the react router tutorial.

When I click the submit button on the form and console log the state and fakeAuth.isAuthenticated, they both return true. However, the redirect is not firing.

Login.js

class Login extends Component {
    constructor(props) {
        super(props);
        this.state = {
            portalId: "",
            password: "",
            redirectToReferrer: false
        }

        this.handleSubmit = this.handleSubmit.bind(this);
    }


    handleSubmit(e) {
        fakeAuth.authenticate(() => {
            this.setState({
                portalId: this.refs.portalId.value,
                password: this.refs.password.value,
                redirectToReferrer: true
            })
        })
        e.preventDefault();
    }


    render() {
        const redirectToReferrer = this.state.redirectToReferrer;
        if (redirectToReferrer === true) {
            <Redirect to="/home" />
        }

Routes.js

export const fakeAuth = {
    isAuthenticated: false,
    authenticate(cb) {
        this.isAuthenticated = true
        setTimeout(cb, 100)
    },
    signout(cb) {
        this.isAuthenticated = false
        setTimeout(cb, 100)
    }
}

const PrivateRoute = ({ component: Component, ...rest }) => (
    <Route {...rest} render={() => (
        fakeAuth.isAuthenticated === true
        ? <Component {...this.props}/>
        : <Redirect to="/" />
    )}/> 
)


export default () => (
    <BrowserRouter>
        <div>
            <Navbar />
            <Switch>
                <Route path="/" exact component={Login} />
                <Route path="/register" exact component={Register} />
                <Route path="/home" exact component={Home} />
            </Switch>
        </div>
    </BrowserRouter>
);
Vincent Nguyen
  • 1,555
  • 4
  • 18
  • 33

5 Answers5

33

You have to return Redirect in render method (otherwise it will not be rendered and as a result redirection will not happen):

  render() {
        const redirectToReferrer = this.state.redirectToReferrer;
        if (redirectToReferrer) {
            return <Redirect to="/home" />
        }
        // ... rest of render method code
   }
Bartek Fryzowicz
  • 6,464
  • 18
  • 27
11

I am now able to redirect to the "homepage" by swapping out <Redirect to="/home" /> with this.props.history.push("/home"); using withRouter. Not sure why the first way would not work though.

Vincent Nguyen
  • 1,555
  • 4
  • 18
  • 33
4

For someone, who uses Hooks, have a look here -> https://reactrouter.com/web/api/Hooks/usehistory Example of use:

import { useHistory } from "react-router-dom";
let history = useHistory();
        
const onSubmit = () => {
    //code
    history.push(`/${link}/${object.id}`)
}
elener
  • 41
  • 1
1

The useNavigate hook is what worked for me. In react-router-dom v6 useHistory was replaced with useNavigate. Here's the code that solved the issue for me:

import { useNavigate } from 'react-router-dom';
const navigate = useNavigate();
const onSubmit = () => {
    e.preventDefault();
    // do what you want with your form data
    navigate('/my-path');
}
Dr.Simplisist
  • 675
  • 1
  • 8
  • 16
0

When we use outside our router declaration. You can just use

this.props.history.push('/url')

inside your function call. Should work with react-router-dom

Pankaj Chauhan
  • 346
  • 3
  • 8