0

Using the ES6 class syntax, I am unable to retain the value of context in other methods inside the class. For example:

class Repos extends React.Component {
  constructor(props, context) { // eslint-disable-line
    super(props, context);
    console.log(this.context.router);
  }

  handleSubmit(event) {
    event.preventDefault();
    const userName = event.target.elements[0].value;
    const repo = event.target.elements[1].value;
    const path = `/repos/${userName}/${repo}`;
    console.log(path); // eslint-disable-line
    this.context.router.push(path);
  }

For the first console log, context persists:

enter image description here

For the second console log, not so much:

enter image description here

How does one handle this.context in methods outside of the constructor, but inside the class?

ilrein
  • 3,833
  • 4
  • 31
  • 48

1 Answers1

5

Have you not forgotten bind function to save context?

If you pass function to some action attribute (onSubmit, for example) you should use bind. React ES6-classes does not autobind methods.

Aleksandr Petrov
  • 1,288
  • 9
  • 13