0

Does class variables in a class need to be a part of the stateObject? I tried below with no luck. Here there is samples with simple variables so I am kind of surprice below does not work (alert says undefined)?

https://www.w3schools.com/react/react_es6.asp

https://codesandbox.io/s/jovial-glade-lfv4f?fontsize=14&hidenavigation=1&theme=dark

import React, { Component } from "react";

class Test extends Component {
  constructor(props) {
    super(props);
    this.variable = "works";
  }

  clicked() {
    alert(this.variable);
  }

  render() {
    return <div onClick={this.clicked}>CLICK ME</div>;
  }
}

export default Test;
1
  • 1
    Try to use arrow function clicked = () => { ... } Commented Jan 9, 2020 at 8:08

2 Answers 2

4

You need to use bind() call to make it work.

constructor(props) {
  super(props);
  this.variable = "works";
  this.clicked = this.clicked.bind(this);
}

for more information on this checkout Handling events in React

Why you have to bind here? so this is because you are using ES6 syntax for your components, and in ES6 class methods are not bound to classes by default, and to be able to use this keyword inside your methods and make it refer to the class instance you have bind your method to the class like in this answer.

Sign up to request clarification or add additional context in comments.

2 Comments

Kind of strange your binding the event. The event actually works. Is it because you need to bind events before you can use local variables within them?
I added more explanation in my answer.
3
import React, { Component } from "react";

class Test extends Component {
  constructor(props) {
    super(props);
    this.variable = "works";
  }

  clicked = () => {
    alert(this.variable);
  }

  render() {
    return <div onClick={this.clicked}>CLICK ME</div>;
  }
}

export default Test;

You can choose not to bind but you need to be adding fat-arrow function syntax in order to make it work.

3 Comments

ah ok now works. So it is not about fat-arrow func or bind, just using arrow function is ok
Thanks for your input, appreciated.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.