0

Im new to react and looking for something equivalent to anglers $state.go. Im using router 4 and does not work for me. Other things Ive seen online seem to be not for router 4. Any help would be great! Thanks

class App extends React.Component{
  ...
  axis.post(/signup,{info})
    .then(function(){
     <Redirect if successful />
  })
}

 <HashRouter>
   <Route exact path='/' component={Home}/>
   <Route path='/login' component={Login}/>
   ...
 </HashRouter >
javascripting
  • 993
  • 3
  • 19
  • 32
  • You could find a very Complete answer here: https://stackoverflow.com/questions/42123261/programmatically-navigate-using-react-router-v4 – maxgallo Aug 06 '17 at 09:08
  • Possible duplicate of [Programmatically navigate using react router V4](https://stackoverflow.com/questions/42123261/programmatically-navigate-using-react-router-v4) – maxgallo Aug 06 '17 at 09:09
  • I did look at the answer. As most proposed answers seems a little too much for trying to have a 'simple' redirect, I tried the suggested which does not work. – javascripting Aug 06 '17 at 09:31
  • answer also uses Browserrouter instead of Hashrouter like I do which I had to use or otherwise I can't refresh a page without getting a 'cannot get ...' error to which the answer again was to use hash router instead of BrowserRouter – javascripting Aug 06 '17 at 09:34

1 Answers1

1

A good way to do this would be through the history library(if you don't have it already, you can do npm install history --save React-Routerv4 uses this library as well.

Here are the docs for it which ReactRouterv4 also links to in their docs: https://github.com/ReactTraining/history

import createHistory from 'history/createBrowserHistory';

class App extends React.Component{
  ...
  axis.post(/signup,{info})
    .then(function(){
   const history = createHistory();
//listen for changes in current location

    const listen = history.listen((location, action) => {
      console.log(action, location.pathname, location.state);
    });
  //push the state as props to the route that will be redirected to
      history.push('/RouteToRedirectTo', { some: stateifneeded });

      //redirect to the route you want
      history.go('/RouteToRedirectTo');
  })
}

 <HashRouter>
   <Route exact path='/' component={Home}/>
   <Route path='/login' component={Login}/>
   ...
   </HashRouter >
Dream_Cap
  • 2,202
  • 1
  • 16
  • 29
  • Thank you. Could you explain { some: stateifneeded }) - what would I pass in here? – javascripting Aug 06 '17 at 09:30
  • If your component(App) has a state like "this.state = { loggedIn: true }", then you could pass it to the component that is being redirected to, and receive that state in the form of props. I don't believe that parameter is required if you don't need {some:stateifneeded}. For example, you would pass it like {logInfo: this.state.loggedIn} if you had some type of state for logged in/logged out. – Dream_Cap Aug 06 '17 at 09:33