React Router vs Angular Router vs Vue Router
We should all agree that one of the most important parts of a SPA (Single Page Application) is a navigation and routing that we are building around it. So, in the following text we are going to create routing in React, Angular and Vue.js framework.
React Router
After we created react app with
npx create-react-app testing-react-router
command, next step is to install React Router, import it in our
index.js
component and wrap ourApp
component in BrowserRouter
Now it's time to create few components that will be added to
Header.js
component. Header will also contain links to the Home, About and Projects page.
After we finish with creating Header, we will add it to the
App
component because we want Header to be visible in our main page. Next we are importing
Route
and adding routes to our previously created pages.
When adding Home route, it's important to add exact attribute. Without exact attribute our home route will always match with all other routes (because all routes contain slash "/").
Okay, we are done and ready to test our routes 🔱
Angular Router
After creating our app with Angular Cli command
ng new testing-angular router
, we are going to add few components (home, about and project) in our project.
ng g c component-name
is the most practical way to do it. Next step is to import RouterModule and our previously created components in our main
app.module.ts
file. We also need to add RouterModule in imports array, call forRoot method and pass in routes as an array.
After our app module is all set, let's display links to pages in
app.component.html
file. We also need to add route to every page using
[routerLink]
directive.
Also, we need to display our component's content somewhere. We will display component's views with placing
<router-outlet></router-outlet>
to app.component.html below links to our pages.
We are ready to test our routes ♻️
Vue Router
It's now turn to test Vue routing. We will use ng cli to create vue app. After creating our app with
create testing-vue-router
, we need to add router to our project with
vue add router
command and define Home, About and Projects routes in index.js file
After we passed routes to our instance of VueRouter
const router = new VueRouter({routes: routes})
, we can import router to main file and add it to the app
Next we are going to add router links to
App.vue
and place
<router-view/>
below for displaying our components content.
Let's run our app with
npm run serve
and see result in browser
It works 🤹🏻♂️
Summary
We learned that routing is inevitable part of any Single Page Application and saw how to add routes and navigation to our React, Angular and Vue project.
For more in depth guides check out these links: angular.io, reactjs.org, router.vuejs.org