3

I'm very much aware of the react-router-dom I want to do a conditional rendering of the component. If use is not logged in redirect him to some third party URL

for example, the below code looks neat and works fine

<Route exact path="/home" render={() => (
  isLoggedIn() ? (
    <Redirect to="/front"/>
  ) : (
   <Home />
  )
)}/>

Let's say in the above example if I want to redirect to https://www.google.com how can I do it?

if I write

 <Redirect to="https://www.google.com"> it gives me error. 

How can I redirect to a third party website?

Harsh Makadia
  • 2,637
  • 5
  • 22
  • 37

5 Answers5

12

You can use a tag for external urls,

<a href='https://domain.extension/external-without-params'>external</a>

but also you can provide component like this:

<Route path='/external' component={() => { window.location = 'https://domain.extension/external-without-params'; return null;} }/>
Akif Hadziabdic
  • 2,241
  • 1
  • 8
  • 20
2

You can use window.open() to redirect to any website.

For example:

window.open('https://www.google.com');

implement redirection in your code:

render () {
  if(this.isLogin) {
    return(/* your components*/);
  } else {
    window.open('https://www.google.com');
    return (<div></div>); //render function should return something
  }
}

You can also specifies the target attribute or the name of the window, for more details, see w3school tutorial about this function.

Danny Lau
  • 116
  • 5
0

Have on mind that you cannot perform that with <Link /> or <NavLink /> since they're mainly for routing throughout Single Page Application.

You should use anchor tag instead. Example: <a href="https://www.google.com">Google</a>.

0

In case you're using Typescript you probably will get the following error with the Accepted Answer:

Type 'string' is not assignable to type 'Location'

To fix that you just need to use window.location.href

<Route path="/external" component={() => {window.location.href = config.UPGRADE_URL return null }} />
Victor Carvalho
  • 905
  • 1
  • 10
  • 18
-1

Can easily use a button just do this:

<button onClick={(e) => (window.location = 'https://www.google.com')}>Click me</button>
Nick Sherman
  • 238
  • 2
  • 9