Creating a Responsive Navigation Bar with React and CSS

Designing responsive navigation menus is crucial for enhancing user experience. In this article, we will explore how to create a responsive navigation bar using React and CSS. We’ll also discuss how to utilize the useMediaQuery hook to make our navbar responsive.

Prerequisites

  • Basic understanding of React, React Router DOM, and React Hooks
  • Familiarity with CSS, particularly Flexbox layout system

Setting up the Development Environment

To start, create a new React project using the following command:
bash
npx create-react-app my-app

Next, install the necessary dependencies:
bash
npm install react-router-dom react-icons react-responsive

Creating the Navbar Component

Create a new file called Navbar.js and add the following code:
“`jsx
import React from ‘react’;
import { NavLink } from ‘react-router-dom’;
import { IoMenu, IoClose } from ‘react-icons/io’;

const Navbar = () => {
return (

);
};

export default Navbar;
“`
Styling the Navbar

Create a new file called Navbar.css and add the following code:
“`css
nav {
display: flex;
justify-content: space-between;
align-items: center;
padding: 1rem;
background-color: #333;
color: #fff;
}

nav ul {
list-style: none;
margin: 0;
padding: 0;
display: flex;
}

nav li {
margin-right: 20px;
}

nav a {
color: #fff;
text-decoration: none;
}

nav button {
background-color: #333;
border: none;
padding: 10px;
cursor: pointer;
}
“`
Making the Navbar Responsive

To make the navbar responsive, we’ll use the useMediaQuery hook. First, import the hook:
jsx
import { useMediaQuery } from 'react-responsive';

Then, update the Navbar component:
“`jsx
const Navbar = () => {
const isMobile = useMediaQuery({ query: ‘(max-width: 1150px)’ });

return (

);
};
“`
Conclusion

In this article, we created a responsive navigation bar using React and CSS. We also utilized the useMediaQuery hook to make our navbar responsive. With this approach, you can easily create a responsive navbar that adapts to different screen sizes.

Leave a Reply

Your email address will not be published. Required fields are marked *