简体   繁体   中英

React router link - how to navigate to absolute path

import { Link } from 'react-router-dom';
...
const Button = () => {
  <Link to="SOME_S3_URL"/>
   <button>Go to S3 URL</button>
  </Link>
}

When I click it, it's not working. Is it possible to do so?

It is not possible to do so as is; the Link component renders an anchor element, something fundamentally different than a button element.

If you need to use your reusable button, something you can do is:

import { useNavigate } from 'react-router-dom';
...
const Button = () => {
    const navigate = useNavigate();

    return (<button onClick={() => navigate("SOME_S3_URL")}>Go to S3 URL</button>);
}

I guess SOME_S3_URL is referring to an URL to Amazon S3, which in that case, is outside of your application.

So you should use a normal <a/> instead since <Link /> is designed for internal navigation.

As for your comment about "creating a reusable button", you just apply CSS to the <a /> element so that it will look like a button. This is a common practice used by multiple popular UI libraries like MUI and Chakra UI.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM