2

I am trying to redirect to an external URL in a react component.

I am verifying when the component is loaded if it contains an access_token in the local storage. If it does not exist I want to redirect to an auth provider to perform login and then to store the token when it redirects back to me.

However I found that assigning a value to window.location or window.location.href or using window.location.replace(someUrl) it does not work, it simply appends the new url to my application url.

Here is my react component where I am doing this:

class App extends React.Component {
  componentDidMount() {
    if (!localStorage.getItem('access_token')) {
      window.location.replace(someUrl)
    } 
  }

  render() {
    return (
      <HashRouter>
        <React.Suspense fallback={loading()}>
          <Switch>
            <Route path="/" name="Home" render={props => <DefaultLayout {...props}/>}/>
          </Switch>
        </React.Suspense>
      </HashRouter>
    )
  }
}

Is there a different way on how the redirect to an external URL should be done in React?

I also tried this one and it does not work, it appends the external URL to the one of my application: React-Router External link

Flowryn
  • 1,378
  • 1
  • 13
  • 28

1 Answers1

-2

Use React Router Redirect component and provide address in to attribute.

<Redirect push to="/somewhere/else" />

https://reacttraining.com/react-router/web/api/Redirect

Zohaib
  • 705
  • 5
  • 11
  • this doesn't work and doesn't answer the question. he meant external links like if your domain is myapp.com -- he wants to be directed to "https://cnn.com" this approach doesn't work. it'll just lead you to `myapp.com/https://cnn.com` which us completely invalid. – JasonGenX Mar 18 '21 at 16:59