Home > other >  unable to access to an url using react-router-dom
unable to access to an url using react-router-dom

Time:10-22

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 !

CodePudding user response:

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>

CodePudding user response:

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.

  • Related