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
This may take less than a minute and end with this message the end –
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
And the code looks like this in VS 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 –
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
UserPage.js
- Refresh your site (npm start) and you should be able to navigate between home page and user page.
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.