React: Button handleClick help [Solved]

Hello,

I am trying to get a button component which is nested in my “CharPic” component to update a value in the state of my App component. I have a handleClick function in my App component which changes the state property menuPage to 0 or 1 depending on the name of a “Button” argument.

There is a button in the “CharPic” component:

It should change which components are displayed. I am trying to make it like a menu in a game where you can switch between inventory and battle screens. When I change the state property menuPage manually, it works.

I can’t seem to get the button to do as I want it. This is what I have so far. I am passing the function handleClick as a property to the “CharPic” component.

The “CharPic” component is then passing the handleClick function to the button component it is rendering. This button has an onClick which activates a sendToParent function, which in turn returns handleClick passing the button’s name as an argument.

I feel like the info from sendToParent is not making it all the way up to the main App component and is getting stuck in the “CharPic” component, but I can’t figure out how to send it further along. Any help would be greatly appreciated!

try binding your handleClick inside your constructor or you can bind it on your buttons inside the render:

constructor(props){
   super(props);
   this.state = {}
   this.handleClick = this.handleClick.bind(this);
}

or inside your render <button onClick={(e)=>this.handleClick(e)}>submit</button>

1 Like

Hey, thank you for taking the time to look at this!

Do you mean the constructor of the App component or one of it’s children? I tried a few variations and it tells me the error:

TypeError: _this2.handleClick is undefined

None of my components besides App had constructors but I added them to test different places to bind handleClick.

I think you need to put handleClick inside the class itself, not above. It’s like @mav1283 said

like,

and below the constructor:

handleClick() {
  //code here
}

so the whole code looks like this:

class App extends React.Component {
  constructor(props){
     super(props);
     this.state = {} //state contents here
     this.handleClick = this.handleClick.bind(this);
  }

  handleClick(e) {
    //code here
  }
}
2 Likes

Ohhhhhhh.

I see now. Thank you very much. It works!

<3

2 Likes

Yes! always remember when using this it is inside the class :slight_smile: Happy Coding!

2 Likes