I'm using React-router and it works fine while I'm clicking into link buttons, but when I refresh my webpage it does not load what I want.
For instance, I am into localhost/joblist and everything is fine because I arrived here pressing a link. But If I refresh the webpage I get: Cannot GET /joblist
By default It didn't work like this. Initially I had my URL: localhost/#/ and localhost/#/joblist and they worked perfectly fine. But I don't like this kind of url, so trying to erase that '#' I wrote:
Router.run(routes, Router.HistoryLocation, function (Handler) {
React.render(<Handler/>, document.body);
});
This problem does not happen with localhost/, this one always returns what I want.
EDIT: This app is single-page, so /joblist don't need to ask anything to any server.
EDIT2: My entire router.
var routes = (
<Route name="app" path="/" handler={App}>
<Route name="joblist" path="/joblist" handler={JobList}/>
<DefaultRoute handler={Dashboard}/>
<NotFoundRoute handler={NotFound}/>
</Route>
);
Router.run(routes, Router.HistoryLocation, function (Handler) {
React.render(<Handler/>, document.body);
});
Solution for Preact with preact-router
Works with refresh and direct access
For those discovering this via Google, here's a demo of preact-router + hash history:
https://jsfiddle.net/developit/gLyL6rbn/
In your index.html
head
, add the following:Then when running with webpack dev server use this command.
--history-api-fallback
is the important partYou can change your htaccess and insert this:
I am using
react: "^15.3.2"
,react-router: "^3.0.0"
,history: "^4.3.0"
,If you do have a fallback to your index.html, make sure that in your index.html file you have this:
This may differ from project to project.
I'm not using server side rendering yet but I hit the same problem as the OP where Link seemed to work fine most of the time but failed when I had a parameter. I'll document my solution here to see if it helps anyone.
My main jsx contains this:
This works fine for the first matching link but when the :id changes in
<Link>
expressions nested on that model's detail page, the url changes in the browser bar but the content of the page did not initially change to reflect the linked model.The trouble was that I had used the
props.params.id
to set the model incomponentDidMount
. The component is just mounted once so this means that the first model is the one that sticks on the page and the subsequent Links change the props but leave the page looking unchanged.Setting the model in the component state in both
componentDidMount
and incomponentWillReceiveProps
(where it is based on the next props) solves the problem and the page content changes to reflect the desired model.Try adding ".htaccess" file inside the public folder with the below code.