reactjs navigation

reactjs navigation

In this article, I am going to create a demo reactjs app that has navigation implemented to move from one view to another.

Pre-requisites

  • VS Code editor or any other editor.
  • Node and npm – download and install the latest stable release from https://nodejs.org/. Node 14 or higher is required for this tutorial.
  • Create a new react app

npx create-react-app react-navigation

create-react-app

This may take less than a minute and end with this message the end –

create-react-app-success

As the output from the command suggests, run these commands –

cd react-navigation

npm start

By this time, we have created a blank reactjs app which is running on localhost:3000

blank react app in localhost:3000

And the code looks like this in VS Code –

blank react app source code

 

Time to implement react navigation.

 

  • Install react-router-dom with this command

               npm install react-router-dom -s

  • Open app.js in VS Code and make following changes –

react router code in app.js

This is the most important step to understand react navigation. Here we import BrowserRouter, Routes and Route components from react-router-dom package and use them in App component html. You can add more Route tags as you add more pages to your site.

 

  • For this example, we need two react components to act as two different pages. Create these two components under a new directory name pages under src folder

 

HomePage.js

sample home page component

 

UserPage.js

sample user page component

 

 

 

  • Refresh your site (npm start) and you should be able to navigate between home page and user page.

 

react navigation demo

 

 

 

Conclusion

React navigation is an important concept in reactjs and almost every app needs to navigate between its views. This article helps in making this concept easy for you to understand and use the code examples given in this article to get started with react navigation.