Home > Back-end >  React navbar not working properly showing error
React navbar not working properly showing error

Time:06-08

i was trying to build a navbar in react .the functionality was to show the bar on button click and withdrow it again on button click . But the functionality is not working showing this error : " Cannot read properties of null (reading 'style')" in console.

my code here:

const menu = document.getElementById('menu');

const closeBar = () =>{
    menu.style.top = '-100vh';
}

const openBar = () =>{
    menu.style.top = '17%';
}
Get Started Home Courses Blog Dashboard Login

CodePudding user response:

In react you work declaratively, this means that you "indicates" to react how the page should look and react takes care of do it, this why you dont manipulate the doom directly in most of the cases. To do that, you could do:

const ParentComponent = () => {
  const [showNavbar, setShowNavbar] = useState(true);

  const handleOnClick = (e) => {
    setShowNavbar(!showNavbar);
  };

  return (
    <div className="App">
      {showNavbar && <Navbar />}
      <button onClick={handleOnClick}>Toggle navbar</button>
    </div>
  );
}

And this shows/hide the Navbar component when the button is clicked

  • Related