I am new to React
and just learning how routing works. hashHistory
(/#/paths/like/this
) works great but browserHistory
(/paths/like/this
) look much better. Obviously, browserHistory
paths do not work right out of the box when I re-open URLs, because the broweser requests /path/on/server
that does not exist.
The question is: Do I have to use server-side rendering (so called isomorphic rendering
) in order to use /nice/paths
and let users open pages directly, or be able to Ctrl+R pages and stay where they are, or there are options to do it keeping just client-side
rendering?
Thanks.
No you can easily use client-side
rendering and allow users to use paths like nice/paths/
.
Since these routes are just a React convenience and does not exist on the server, going directly to them throws an error as the pages simply do not exist. To solve this you should point all your routes to index.html
(your entry point for the application) in the server and then let React take over to handle the path.
In Express it would be done like this:
app.get('*', function(req, res) {
res.sendFile(__dirname + '/public/index.html')
})
For an Apache server this would be the .htaccess
:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]
</IfModule>
For other server side languages they have their own methods and this pointing to index.html
basically works for all SPA frameworks like Angular etc as the logic is the same.