Elad Karni Elad Karni - 3 months ago 273
React JSX Question

Implementing a Drawer & AppBar with Material-UI + React {Cannot read property 'open' of null}

So I'm trying to use

React
&
Material-UI
to create an app, so I managed to get the AppBar up and running but am having some issues getting the Drawer to work.

I keep getting an
error: cannot read property open of null
, and have tried to figure out what the issue is to with no success. I found a 2 post on Stack about this exact issue, both of them don't have an answer that was able to resolve my problem

Having trouble using Appbar + Drawer (Material UI + ReactJS)

What is Uncaught TypeError: Cannot read property 'open' of undefined for AppBar + Drawer component (ReactJS + Material-UI)?

This is my current code:



constructor() {
super();
this.handleToggle = this.handleToggle.bind(this)
this.handleClose = this.handleClose.bind(this)
this.setState = {
open: false
};
}

handleToggle = () => this.setState({open: !this.state.open});

handleClose = () => this.setState({open: false});

render() {
return <MuiThemeProvider muiTheme={getMuiTheme()}>
<AppBar
onLeftIconButtonTouchTap={this.handleToggle}
onLeftIconButtonClick={this.handleToggle}
title="How long have you been alive?"
iconClassNameRight="muidocs-icon-navigation-expand-more" />
<Drawer
docked={false}
width={200}
open={this.state.open}
onRequestChange={(open) => this.setState({open})}
>
<MenuItem onTouchTap={this.handleClose}>Menu Item 1</MenuItem>
<MenuItem onTouchTap={this.handleClose}>Menu Item 2</MenuItem>
</Drawer>
</MuiThemeProvider>
}





(snippit isn't suppose to run, just show my relevant code)

I thought maybe binding
this
to
render
would help, but it did not :(

Answer

Problem in your code is you are not setting state in constructor. this.setState in constructor is wrong, it needs to be replaced with this.state

constructor() {
    super();
    //...other lines of codes that you may intend to write

    this.state = {
      open: false
    };

  }

this.setState() is a method that you call to update component's state from any method of a Component-Class except render() and constructor()