I am trying to make my navbar mobile responsive, problems are (in mobile view): 1.Initially we get FaTimes (x) button instead of FaBars (hamburger). 2.And when we click on those buttons, the navbar does open and close but the button doesn't toggle, it only renders FaTimes (x) button.
I want to get a) FaBars at first and b) when we click on it to open and close navbar the buttons shall toggle between FaBars and FaTimes.
this is my NavBar Component:
import React, { useRef, useState } from "react";
import "../styles/styles.css";
import { NavLink } from "react-router-dom";
import { FaBars, FaTimes } from "react-icons/fa";
function NavBar() {
const navRef = useRef();
const [isOpen, setIsOpen] = useState(false);
const showNavBar = () => {
setIsOpen(!isOpen);
};
return (
<>
<nav
className={`mobile-nav ${isOpen ? "responsive_nav" : ""}`}
ref={navRef}
>
<div className="itemL">
<NavLink to="/" exact activeClassName="active">
mjshubham21
</NavLink>
</div>
<div className="itemR">
//Nav links...
</div>
</nav>
<button className="nav-btn" onClick={showNavBar}>
<FaBars /> // I want this initially ad then toggle as we tap on it.
</button>
<button className="nav-btn nav-close-btn" onClick={showNavBar}>
<FaTimes />
</button>
</>
);
}
export default NavBar;
I'm not sure if you're trying to manage it all in CSS with your responsive_nav
class, but it looks as though there is currently no logic for displaying (or not) the buttons?
You could actually consolidate those buttons into one button, and just toggle between the two icons. If you change this:
<button className="nav-btn" onClick={showNavBar}>
<FaBars /> // I want this initially ad then toggle as we tap on it.
</button>
<button className="nav-btn nav-close-btn" onClick={showNavBar}>
<FaTimes />
</button>
for this, using your isOpen state bool to change between them:
<button className="nav-btn" onClick={showNavBar}>
{isOpen ? <FaTimes /> : <FaBars />}
</button>