How do I navigate to another page in React or Vue?

An article, posted more than 5 years ago filed in components, react, style, css, html, frontend, link, a, href, vue & coffeeandorange.

Congratulations, you started working with one of the popular front-end frameworks. Both Vue and React are excellent choices to create rich and reactive applications. But sometimes, you ‘just’ want to show the user another page. Whether it is a simple about page, or another ‘section’ in the app. In this post I will cover both Vue en React and, little bonus, “React on steroids”, NextJS.

It is important to know that you need a router to make in-app pagination work. If you look up router and your favourite framework you’re probably find a way to do it, accompanied with some ways to actually not do it. Hence, here I’ll focus on the right way.

The basics of every link

While you can make everything clickable (or touch-able), it is important that enabling navigation between pages was already a core concept when the web was invented. Even when writing webpages using React, Vue, or most other JavaScript frameworks, it ends up as HTML to the browser (with JavaScript & CSS). HTML stands for Hyper Text Markup  Language and HyperText is text with hyperlinks. Hyperlinks in HTML are written as follows:

<a href="https://example.com">Example link</a>

So why is this important? On parsing code presented as above, the browser does the following:

While the code above looks easy, it is easy with modern frameworks to create something like this:

<div onclick="open('https://example.com')">Example link</div>

This is clickable, and yes, it might navigate you to example.com, but shares none of the desirable characteristics of the well known hyperlink.

The boring fact…

The boring fact is that the above code, yes with the <a href=…, works in every framework. In the next few posts I’ll dive into the ways to make it  work more natively in the frameworks mentioned earlier, often resulting in much faster page loads when you stay within your React/Vue or whatever application. Also, I’ll give a bit of a review of the good parts of these and make sure you don’t use the bad parts (if any). To stay up to date, make sure you subscribe to my mailinglist!

Op de hoogte blijven?

Maandelijks maak ik een selectie artikelen en zorg ik voor wat extra context bij de meer technische stukken. Schrijf je hieronder in:

Mailfrequentie = 1x per maand. Je privacy wordt serieus genomen: de mailinglijst bestaat alleen op onze servers.