Home > Software engineering >  My onClick function is not working, and the menu is not showing
My onClick function is not working, and the menu is not showing

Time:06-06

function Navigation() {
  const [open, setOpen] = useState('false');
  return (
    <div>
      <nav>
        <div className="siteName">Site Name</div>
        <ul
          className="navLinks"
          style={{transform: open ? 'translateX (0px)' : ''}}
        >
          <li>
            <a href="/">Home</a>
          </li>
          <li>
            <a href="about">About</a>
          </li>
          <li>
            <a href="experience">Experience</a>
          </li>
          <li>
            <a href="contact">Contact</a>
          </li>
        </ul>
        <i onClick={() => setOpen(!open)} className="fa-solid fa-bars burger" />
      </nav>
    </div>
  );
}

I have the onClick function in the hamburger menu and set state. But when I was trying out the button, it is not working, and the menu is not showing up.

CodePudding user response:

You are passing a string containing the word "false" to the useState hook.
In-order to pass a boolean value, you need to remove the quotation marks.

Example:

const [open, setOpen] = useState(false);

CodePudding user response:

You made boolean value string inside useState

const [open, setOpen] = useState('false'); <--here

Since if string has value it is considered to be true.

Recommendation

I recommend you to install library clsx for conditionally render CSS in React.

Navgation.js

import "./styles.css";
import { useState } from "react";
import clsx from "clsx";

export default function App() {
  const [open, setOpen] = useState(false);
  return (
    <div>
      <nav>
        <div className="siteName">Site Name</div>
        <ul className={clsx("navlinks", open ? "openStyle" : "closeStyle")}>
          <li>
            <a href="/">Home</a>
          </li>
          <li>
            <a href="about">About</a>
          </li>
          <li>
            <a href="experience">Experience</a>
          </li>
          <li>
            <a href="contact">Contact</a>
          </li>
        </ul>
        <button onClick={() => setOpen(!open)}>OPEN</button>
      </nav>
    </div>
  );
}

And add stylings for you opening and closing menu. Inside CSS file add this

style.css

.openStyle {
  color: red;
}

.closeStyle {
  color: black;
}

Working demo

Useful link:

3 Ways Conditionally Render CSS in React

  • Related