suheb suheb - 11 days ago 8
React JSX Question

Page reloads when using href to change route in FlowRouter

I'm using FlowRouter for routing in my Meteor+React app. I've defined some routes like this:

FlowRouter.route('/about', {
action: () => {
mount(MasterLayout, {
content: <AboutPage />,
});
},
});


FlowRouter.route('/terms', {
action: () => {
mount(MasterLayout, {
content: <TermsPage />,
});
},
});


Now when I click on a link like
<a href="/about">About</>
, it reloads the entire page instead of just changing the content.

Also, if I use
FlowRouter.go('/about')
, it works fine and doesn't reload the page, only changing the content.

Please tell me what's happening here.

Answer

There may be more than one reason for this to happen, but this is what I have in mind:

It is because your <a> tag is possibly inside an element (parent or grandparent or grand-grand parent ... ) having a click event handler, and that handler calls to .stopPropagation(). This causes the event stop bubbling up to the document click event handler, added by FlowRouter, which is in charge of changing the route for you. Therefore the normal behaviour, when an <a> tag is clicked of browser, is executed which is to change the route and reload the page.

To fix this you could try to remove that .stopPropagation(). If you could not for some reasons, you could simply call e.preventDefault() and FlowRouter.go yourself.

If you are interested in how it works, here are some more information to dig into: