I'm fairly new to react and have a basic understanding of how it works. Using the react-router-dom package, I have a homepage set up with 3 links leading to /about, /post, and /account. All works as expected when visiting the homepage and clicking each of these links.
The problem I encounter is trying to load a page by going directly to the pages url. For example, typing www.xxx.com/about will load a 404 page. As I mentioned above, loading the homepage and clicking the about link will work perfectly fine, but trying the url path of the about page will not work. Why is this happening and is there a way to fix this?
When you navigate through React Router, two things happen:
The idea is that when you a page from scratch, you have to load the React application from the server, but when you navigate from page to page, it is all handled client-side (except perhaps for API calls to get data).
Your problem is that you haven't done anything to make the server support that route so when the first page a browser loads (including refreshing or opening a link in a new window) isn't the homepage, you hit a 404 error instead.
There are a few basic approaches to doing that.
Configure your server so that any request for a route which should be handled by the React Router serves up the HTML document which bootstraps your HTML document.
Currently you only have (probably) the path / serve up that document.
This has a couple of disadvantages:
While I don't recommend this approach, here is a question about how to configure Apache HTTPD to do this. Other HTTP servers will need configurations specific to them.
You can avoid having the URLs for your routes pointing to different paths on the server by changing the fragment identifier in the URL instead of the path.
This is done by using <HashRouter> instead of <BrowserRouter>.
Hashbangs were the approach used by SPAs before the introduction of pushState and friends by browsers.
This avoids breaking 404 errors.
You produce a version of the React bootstraping document tailored for each route.
This is the approach used by Gatsby which makes it pretty easy.
This does the same thing, but rather then creating a big file of static HTML documents which all have to be replaced when you do updates, you generate the documents with a fairly traditional server side approach.
Next.js takes this approach and, again, makes it quite easy. You need more specialist hosting than you do for simple static files though.