最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - React router link - how to navigate to absolute path - Stack Overflow

programmeradmin1浏览0评论
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?

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?

Share Improve this question asked Aug 4, 2022 at 1:19 CCCCCCCC 6,52110 gold badges61 silver badges145 bronze badges 5
  • Assuming you are routing to a url outside of your app, use an anchor tag and href – Andrew Commented Aug 4, 2022 at 1:23
  • @Andrew I'm creating a reusable button, so I can't use anchor tag – CCCC Commented Aug 4, 2022 at 1:25
  • Absolute paths start with a leading "/" character, but it looks like you are trying to link to a URL outside the app, you will need to use a regular anchor tag for this. react-router-dom only links to internal pages rendered by the router. What is an actual target path value you are trying to use? "SOME_S3_URL" isn't very helpful. – Drew Reese Commented Aug 4, 2022 at 1:41
  • Possible duplicate of stackoverflow./questions/61130162/… – Producdevity Commented Aug 4, 2022 at 1:42
  • If you are routing outside of your app, you cannot use react-router-dom. That library is only for SPA "fake" routing – Andrew Commented Aug 4, 2022 at 20:48
Add a ment  | 

2 Answers 2

Reset to default 4

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 ment about "creating a reusable button", you just apply CSS to the <a /> element so that it will look like a button. This is a mon practice used by multiple popular UI libraries like MUI and Chakra UI.

It is not possible to do so as is; the Link ponent 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>);
}
发布评论

评论列表(0)

  1. 暂无评论