Mahfuz Anam Tasnim
Mahfuz Anam Tasnim

Reputation: 27

React navbar not working properly showing error

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

Upvotes: 0

Views: 696

Answers (1)

Angel Hdz
Angel Hdz

Reputation: 775

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

Upvotes: 1

Related Questions