Ad

The Different Behavior Between Link And Anchor Tag In React-router

- 1 answer

I think it is a convention to use Link over Anchor tag. From my understanding, Link tag will be translated into anchor tag into html. However, from my observation, Link will render the page in the client side and also cache the page, the anchor tag will render the page in the server side.

Here is the code, I have one component which has method willTransitionTo

willTransitionTo: function (transition, params, query, callback) {
      console.log('transition to');
    }

When I have another component to link this component, if I am using Link from react-router, the log will be printed in the browser console. The interesting thing is that it cached the data on the second time when I link to this page (no data fetched from the network). On the other hand, the log will be printed in the server side console if I am using anchor.

I understand what anchor does, but I dont understand why anchor in the Link is client side rendering. Is it an expected behavior ? Also, how Link know how to cache the data if I dont misunderstand.

Many thanks in advance

Ad

Answer

I'm unsure exactly what you're asking. I think what you're asking is why the URL in the browser changes without it generating a new HTTP request. The reason is HTML5 history.

HTML5 history allows us to have nice URLs in front-end routing instead of the old style hash based URLs, i.e. /page instead of /#page. In this sense, React Router is nothing more than a wrapper around HTML5 history.

When using HTML5 history, it's important to make sure the back end is configured to serve up the pages at all your routes. e.g. You can have a front-end transition from / to /cart, but if you then reload the page you'll get a server error if your server hasn't been configured to serve the endpoint /cart. This is also important for older browsers (e.g. IE9) that don't support HTML5 history, which will gracefully degrade to traditional HTTP requests.

For more on HTML5 history, there's the always readable CSS Tricks. https://css-tricks.com/using-the-html5-history-api/

Ad
source: stackoverflow.com
Ad