React.js Sidebar Navigation
Hi friends, In this blog I will share with you how to create Sidebar navigation in React.js
We are going to use react-router-dom
dependency for the router. For more detail refer to this doc.
In this react-router-dom
, we can do various types of navigations. But here I will deal with only Sidebar navigation.
Let us go with the example
Create a react.js project.
For create react.js application follow this setps.
$ npx create-react-app react-sidebar-project
$ cd react-sidebar-project
After you created react project then moved to the project folder.
Install all the required dependencies
$ npm install react-router-dom react-icons
react-router-dom — for routing one page to another page.
react-icons — for showing the various icons.
Create the following folder and files for Sidebar.
$ cd src
$ mkdir components
$ touch Navbar.css Navbar.js SidebarData.js
Create SidebarData.js
SidebarData.js file is for showing options of the left bar menu navigations. We are showing each item with icons. Here we have the following three screens (Home, Reports, Products)
Create Navbar.js
In the Navbar.js file, set the navbar toggle button. And render the item in the sidebarData.js file.
Using navbar-toggle we have open and hide left bar menu.
Create Navbar.css
The above image shows the styles for the navbar.
Then move to create pages.
Create pages
Inside the src
folder create a folder called pages
.
$ mkdir pages
$ cd pages
$ touch Home.js
$ touch Product.js
$ touch Reports.js
In that pages
folder, we have the following three files. (Home.js, Product.js, Reports.js)
Sample code for pages
The above is a simple example of Home.js. Like this, we need to create Products.js, Reports.js files.
After created three pages, set route for pages.
Set App.js file
The above image shows the App.js file.
In this App.js import the following files.
- Navbar components
- Home page
- Products page
- Reports page
And imports Router, Switch from react-router-dom
.
Set index.js file
The above image is the example of index.js file.
Sample output:
Thank you for reading. Have a nice day!