i want to add a onclick event to my navbar button but when i add the eventistener everything disappears. here’s my code:
import React from "react";
import {Bars3Icon} from '@heroicons/react/24/solid'
const Navbar = () => {
let btn = document.querySelector('icon');
let menu = document.querySelector('menu1');
btn.addEventListener('click' , () => {
menu.classList.toggle('hidden');
})
return (
<div className="bg-[#1f1e20]">
<div>
<button id="icon"><Bars3Icon className="text-white w-8 h-8 relative left-[320px] top-2" /></button>
<ul id="menu1" className="grid text-white text-center gap-4 p-4 ">
<a href=""><il>
Home
</il></a>
<a href=""><il>
About
</il></a>
<a href=""> <il>
Contact
</il></a>
</ul>
</div>
</div>
)
}
export default Navbar;
idk what am i missing i reviewed some source codes aswell.
2
Answers
You’re kind of going about this all wrong. You are not using React the way it is meant to be used, relying on attaching and removing properties via query selection. Try thinking about it the "React" way.
If you want to toggle on a class, create a state variable that saves the value between re-renders.
Then you should change your button component to use the onClick props.
Finally, toggle your class using a ternary operator;
Looks like you’re probably missing the
class/id
in thequerySelector
.Make sure you add the correct class/method for
icon
andmenu
in the querySelector.Also, try not to manipulate DOM elements directly in react.
You could use React’s state and event handling to achieve the desired behavior.
This should give the desired result