Routing helps users to switch between views in a web application depending on an action or request. Users can switch between pages when they click a link, button, icon, image, or other component within the program.
1. Installing the React-Router
React uses an external library to manage routing however, before we can utilize that library. we have to include routing in our project, So we must first Execute this command in the project directory of your terminal.
install react-router-dom@6 with npm
2. Configure the React-Router
You must import BrowserRouter from the react-router-dom in the base file, index.js, to Setup React Router in your project.
3. Setup React Routes
Now that React router has been successfully imported and installed in our project, the next step is to implement routing using React router.
Hence, we need to configure all our routes in the components to which we want to navigate.
The TabOne page, the TabTwo Page, and the TabThree Page would be the first three pages we would develop. Once the pages have been successfully configured, we can import routes in the App.js file, which acts as the framework for our application.
As we can see from the code above, we utilized React Router Dom’s Routes and Route components to import and declare the routes we needed. The Routes tag encloses all Routes, and all Routes have the following characteristics:
Path: This indicates the route we want users to take to get to the set component, as the name suggests. For instance, if we set the path to /tab-two, the user who adds /tab-two to the URL link will be redirected to that page.
Element: This indicates the Component Name of your Project.
4. Access Configured Routes with Links
We will develop a NavBar component and position it at the beginning of our routes in the App.js file.
Now let’s add Links to the NavBar as mentioned below:
Here, we first imported Link from react-router-dom before adding the property depending on the path we defined while defining our routes. We can access specified routes by adding links to our React application, which is extremely easy to do.
5. Implement Active Links
Users should be able to recognize the specific link they are now travelling to by giving it a distinct colour from other nav links, adding extra styles like underlining, and so on when adding links to a navbar. Using the NavLink component compared to the Link component, which evaluates whether a user recently navigated by adding an active class to such link, simplifies managing and implementing the active link functionality in React. The NavLink component has replaced the Link component in the NavBar Component.
Frontend :
I hope it’s useful. Happy Learning!!
You made routing look like a piece of cake!!
well explained, keep posting similar topics
Nice blog… Keep Writing Pallavi.