Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React-Router Router.HistoryLocation refreshes the page

I am working on React-Express-Node application and focussing on SPA. I am using the react-router.

My server.js file looks like this (only routing part):

app.use(function(req, res, next) {

    Router.run(routes,function(Handler, state) {
        var ele = React.createElement(Handler);
        res.render(path.join(__dirname +  '/public/index'), {html: html});
    });

    next();

});

And the routes file has this code (pasting the main part):

module.exports = (
    <Route name="app" path="/" handler={Main}>
        <Route name="about" path="about" handler={About}/>
        <Route name="about/id" path="about/:id" handler={About}/>
        <DefaultRoute name="default" handler={Home} />
    </Route>
);

And client.js looks like this:

Router.run(routes, function(Root,state){
    React.render(<Root />,document.getElementById('app'));
});

This setup works fine without any problem.

Now, I want to use the History API pushstate so that i can have better urls and get rid of #. To do that, I added Router.HistoryLocation as the second parameter in client.js and it works, it removes the # and gives clean urls. But however, my page refreshes which I don't want.

I have searched this all over and found couple of solutions but they are either using Flux or a custom router. I am surely missing something related to state but not able to figure out. Can someone point me to the right direction ?

like image 897
Abhishek Saha Avatar asked Nov 09 '22 06:11

Abhishek Saha


1 Answers

It is entirely possible to use Router.HistoryLocation with express server rendered SPA app (I'm doing it now).

You need to tell the server.js file where to get the history, i.e. req.url... like this.

Router.run(routes, req.url, function(Handler, state) {
    var ele = React.createElement(Handler);
    res.render(path.join(__dirname +  '/public/index'), {html: html});
});

If the server is set up correctly, the next item to check is how you're transitioning to the routes. Using a traditional anchor <a/> tag will always refresh the page. React Router has provided their own <Link/> component that allows you to navigate to your routes without causing a page reload. You can also look into calling transitionTo() directly on your router to cause a navigation as well.

Also, when a <Link/> tag is active it will also pass an active class to the tag so css can style it accordingly.

Link

<Link to="route" props={} query={}>My Link</Link>

Navigation

router.transitionTo('route', params, query);

Check out the Link Docs and Navigation Docs.

like image 180
BradByte Avatar answered Nov 14 '22 22:11

BradByte