DEV Community

Cover image for How to add Routing in React.JS
Sharoz Ijaz
Sharoz Ijaz

Posted on • Edited on

How to add Routing in React.JS

Learning new things is hard and cumbersome, i recently started learning React and find it hard to understand some concepts but then i researched on how to keep motivating my self-learning and One helpful tip i get was it to share what you learn and you will find it easy.

So in the past few days, I wrapped my head around React.js and understand the core concept of react which was Routing, Routing helps us navigate different pages on our website without reloading the whole website, i found out that there are many routing libraries out there but the best one was " React-Router-Dom ".

In this Blog, i will share my understanding of React Routing using React-Router-Dom.

First, we need to create a small app/website, which at least has 3 pages for navigating, i will not fill the whole website with text and images just the main part so i can distinguish different pages.

I am calling my website Lofi Academy, i was listing Lofi Music when i came up with this idea and so name it after it.

I started the project by creating a react app by running "create-react-app lofi-academy", it take few seconds to load all the files, and then i opened vs code and started cleaning boilerplate stuff like in "App.js" file, and then i Install 2 libraries from NPM, React-Router-Dom, and SASS.

after the setup complete mean after i set up the development environment for my project, i created 2 folders "Components" and "Pages", in the component folder i will store the components like the navbar and in the page, i will keep my all pages which are Home, About and Contact.

In the image below you can see i have built the front-end of the website, it's simple, not look nice but will work for learning.

Home Page

Now comes the part for which i wrote this blog, i imported "Browser Router" from "react-router-dom" and place it in an index.js file around App.js, and then imported "Route and Routes" inside App.js and wrapped them around the Home Page, About Page and Contact Page.

See the Code below for a better understanding...

App.js
Screenshot of App.js file

Navbar.js
Screenshot of navbar.js file

Index.js
Screenshot of Index.js file
I then imported "Link" and "Outlet" in my Navbar component and placed "Link" around the nav links and "Outlet" at the bottom after the Nav Div end but before closing the .

And this is how i React-Routing Work,

Top comments (1)

Collapse
 
michthebrandofficial profile image
michTheBrandofficial

I recently went through the hell of trying to wrap my head around learning React. But just yesterday I made an app that also has React routing and it was actually very easy to understand.