esausilva
esausilva

Reputation: 2116

How to properly Redirect with React Router 4?

A little background. I am using Firebase Authentication (GitHub, Twitter and Facebook), when the user gets authenticated, the app should redirect to Updater component from the SocialButtonList component.

Now I am trying to use Redirect to: string when the user gets authenticated, but for some reason is not working, maybe I am misunderstanding the docs.

My top level container

const App = () => {
  return (
    <Router>
      <div>
        <Switch>
          <Route path='/updater' component={Updater} />
          <Route exact path='/' component={Login} />
          <Route component={NoMatch}/>
        </Switch>
      </div>
    </Router>
  ); 
}

Login.js

const Home = () => {
  return (
    <Content align='center'>
      ...
      <SocialButtonList size={SOCIAL_BUTTON_SIZE_BIG} />
      ...
    </Content>
  );
}

SocialButtonList.js This component handles the authentication logic and upon authenticating I call authHandler and from here I am attempting to redirect to the 'Updater' component.

authHandler = authData => {
  if (authData) {
    <Redirect to='/updater' />
    console.log('AUTHENTICATED');
  } else {
    console.info('User is signed out!');
  }
}

In console I can see AUTHENTICATED message, but the app does not redirect. How can I properly redirect to Updater component?

Update I found a way to redirect using withRouter. See my answer below in the answer section.

Upvotes: 0

Views: 619

Answers (1)

esausilva
esausilva

Reputation: 2116

Well, I found my answer using withRouter instead of Redirect

import { withRouter } from 'react-router-dom';
...
authHandler = authData => {
  if (authData) {
    //<Redirect to={Updater} />
    this.props.history.push('/updater');
    console.log('AUTHENTICATED');
  } else {
    console.info('User is signed out!');
  }
}
...
export default withRouter(SocialButtonList);

This successfully redirects to Updater component.

Now I am wondering, is there a way to get Redirect to work?

Upvotes: 1

Related Questions