0

How can I push a route to history conditionally using react router 4? I get the error 'history.push is not a function'.

I am not looking for a redirect, but something with which the back button in the browser also works.

import React from 'react';
import ReactDOM from 'react-dom';
import {BrowserRouter, Switch, Route, Redirect} from 'react-router-dom';


import Signup from './components/Signup';
import Welcome from './components/Welcome';


class App extends React.Component {

    constructor() {
        super();
        this.state = {
            isLoggedIn: false
        };
    }

    render() {
        return (
            <BrowserRouter>
                <div>
                    <Route exact path="/signup" component={Signup}/>
                    <Route exact path="/welcome" component={Welcome}/>
                    <Route exact path="/" render={() => (
                        this.state.isLoggedIn ?
                            history.push('/welcome') : history.push('/signup')
                    )}/>
                    <Redirect to="/"/>
                </div>
            </BrowserRouter>
        );

    }
}


ReactDOM.render(<App/>, document.getElementById('root'));
Kaya Toast
  • 5,267
  • 8
  • 35
  • 59
  • This might help : https://stackoverflow.com/questions/42474176/using-conditional-component-with-the-same-route-path-in-reactjs – Dev Sep 14 '17 at 06:45
  • I've seen that. It doesn't affect this history, it just displays the components conditionally – Kaya Toast Sep 14 '17 at 06:46

1 Answers1

2

There is an option on the Redirect component to do exactly what you want.

<Redirect to="/" push />

Will do the navigation, and also push onto the browser history

history.push always felt wrong to me :)

Mikkel
  • 7,693
  • 3
  • 17
  • 31