Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reactjs this.setState is not a function error

Tags:

reactjs

Im novice to React js, i don't know whats wrong with below code, but i'm getting setState is not a function error.Please help me to fix this.

class AppBarLayout extends React.Component {
  constructor(props) {
      super(props);

      this.state = {
        visibleSideBar:true,
        slide:""
      }
  }
  showProfile(){

    this.setState({
        slide:'slide'
    });
    console.log(this.state.slide);
  }
  render(){
    return(
            <div>
        <header>
          <NavBar show={this.showProfile}/>
          <Profile slide={this.state.slide} />
        </header>
      </div>
    );
  }
}
export default AppBarLayout;
like image 940
veeran Avatar asked Feb 19 '17 12:02

veeran


2 Answers

You need to bind this.showProfile in the component constructor

this.showProfile = this.showProfile.bind(this)

More detail about this on the Handling Events page of the React doc : https://facebook.github.io/react/docs/handling-events.html

like image 72
Delapouite Avatar answered Sep 28 '22 12:09

Delapouite


Expanding on Delapouite's answer if you don't like to bind every function in the constructor you can use arrow functions to automatically bind to the correct context.

For example:

class AppBarLayout extends React.Component {
  constructor(props) {
      super(props);

      this.state = {
        visibleSideBar:true,
        slide:""
      }
  }

  // Now showProfile is an arrow function
  showProfile = () => {
    this.setState({
        slide:'slide'
    });
    console.log(this.state.slide);
  }

  render(){
    return(
      <div>
        <header>
          <NavBar show={this.showProfile}/>
          <Profile slide={this.state.slide}/>
        </header>
      </div>
    );
  }
}
export default AppBarLayout;
like image 26
César Alberca Avatar answered Sep 28 '22 14:09

César Alberca