user17049514
user17049514

Reputation:

unable to access to an url using react-router-dom

I imported that library :

import { Redirect } from 'react-router-dom';

I have this code :

const test =  () => {
    return <Redirect to="https://www.google.fr/" />
    }
  };

Using that button :

<Button variant="outline-success" onClick={() => test()}>Search</Button>

When I click on that button there is no effects ...

Could you help me please ?

Thank you !

Upvotes: 0

Views: 851

Answers (2)

Houssam
Houssam

Reputation: 1877

React Router is meant for internal navigation within your application and can only redirect to internal routes.

In order to redirect to an external url, you can do the following:

const test =  () => {
    window.location.href = "https://www.google.fr/";
  }
};

If you want to have a clickable button that links to your external url, then using the a tag with the external url as the href property is a better solution, and you can then customize the styling of your a link to make it look like a button.

Upvotes: 1

Matthew Kwong
Matthew Kwong

Reputation: 2957

First, this is not how Redirect supposed to work. You are supposed to redirect to an internal link, not external.

Second, You are trying to return a component in a onClick event handler. Clearly, it will do nothing.

Just use normal <a> for external links. Or make the Button component an a and pass href="https://www.google.fr/" to it.

e.g. this is how MUI do it:

<Button component="a" href="https://google.com">To Google</Button>

Upvotes: 2

Related Questions