简体   繁体   中英

Anchor links working locally but not when deployed (React)

I have a one page react app and I have a menu with anchor links set up like this:

<a href="/App#story" class="font-medium text-gray-100 hover:text-red-600">Story</a>

And in the target div, I have it like this:

<div id="story" class="py-16 xl:py-36 px-4 sm:px-6 lg:px-8 bg-black overflow-hidden">

When I do npm start to run the page locally, the anchor links work as intended. When I deploy it to the web, the links give me a 404.

Why would this happen?

As far as I am aware you can not use <a> tags for internal navigation in react. I don't know why it works locally for you.

With react you are creating single page applications (SPAs), you have 1 html page that can be found in the public folder. If you created the app using create-react-app , you will see within it, an element such <div id=root> </div> . That is the targetted rendering location, where you will be rendering the entire app by dynamically changing the html within it as you interact with the page.

However, when you typically click on an <a> tag, we are usually taken to different html page. Here I would assume the server is trying to retrieve either the App.html page or index.html page from within public/App folder.

React does not typically come in with built in routing functions/components. It leaves it up to the user to implement. So user's usually turn to a package like react-router along with react-router-dom/native (depending on react or react native) to get those functionalities.

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