0

Hello I am a student learning about the MERN stack. I am currently working on a project to create a responsive navigation bar.

My code is showing no issues but I receive an error message on trying to execute the hamburger functionality of the navigation bar.

I have done some research and understand it might be a problem with my this.setState argument but I do not know how to correctly resolve the problem using standard functions. The project I am working on is using arrow functions and I want to practice my skills without copying everything blindly.

The error message is below.

Error

My code snippet is below.

import React from "react";

import NavigationBar from "./Components/NavigationBar/NavigationBar.js";
import SideDrawer from "./Components/SideDrawer/SideDrawer.js";
import BackDrop from "./Components/BackDrop/BackDrop.js";

class App extends React.Component {
  state = {
    sideDrawerOpen: false,
  }; 

  drawerToggleClickHandler() {
    this.setState(function prevState() {
      return {
        sideDrawerOpen: !prevState.sideDrawerOpen,
      }; 
    });
  } 

  render() {
    let sideDrawer = null;
    let backDrop = null;

    if (this.state.sideDrawerOpen) {
      sideDrawer = <SideDrawer />;
      backDrop = <BackDrop />;
    }

    return (
      <div style={{ height: "100%" }}>
        <NavigationBar
          drawerClickHandler={this.drawerToggleClickHandler}
        />
        {sideDrawer}
        {backDrop}
        <main style={{ marginTop: "64px" }}>
          <p>This is the page content</p>
        </main>
      </div>
    );
  }
}

export default App;

The project I am working on.

Video rescource

  • 1
    Change `drawerToggleClickHandler() {` to `drawerToggleClickHandler = () => {` – Yousaf Apr 30 '21 at 16:44
  • 1
    Check out [this](https://reactjs.org/docs/faq-functions.html#how-do-i-bind-a-function-to-a-component-instance) section regarding binding functions to the component instance in the React docs. – Tom Apr 30 '21 at 16:46
  • 1
    state initialization should be inside constructor. – Berk Kurkcuoglu Apr 30 '21 at 16:48

0 Answers0