1

This is what I do when I want to make this of my class functions bind to the class (component) instance. Is there any easier/more proper way to do this in React?

class App extends Component {

  state = {
    currentSection: 1,
    message :{text:''}
  };

 
  constructor(props) {
    super(props);
    this.prevSection = this.prevSection.bind(this);
    this.nextSection = this.nextSection.bind(this);
    this.mobileChanged = this.mobileChanged.bind(this);
  }
}
Ehsan88
  • 3,569
  • 5
  • 29
  • 52
  • 1
    Another alternative is not to use classes. Then you can avoid usage of `this`. Using bind as you have done will make the methods available on the prototype. If you don't care if the methods are accessible until after the constructor has been called, use an arrow function. https://stackoverflow.com/questions/31362292/how-to-use-arrow-functions-public-class-fields-as-class-methods – evolutionxbox Sep 10 '21 at 14:45

2 Answers2

2

If I recall correctly, if you change:

function nextSection() {...}

to

const nextSection = () => {...}

After this change, you can remove this and the bind

Please let me know if your component will remain as functional like it was before. I'm not sure if it this will change the behaviour.

Wojtek322
  • 584
  • 7
  • 20
  • Actually, there must not include the `const` but just `nextSection = () => {...}`. Just like you, I've been giving up on the class component so long that I've nearly forgotten how to write it. ;) – Ryan Le Sep 10 '21 at 15:02
2

You could use arrow function instead of class method

With arrow function, there will be no this context so you won't have to bind it

class App extends Component {
  state = {
    currentSection: 1,
    message: { text: '' },
  };

  prevSection = () => {}

  nextSection = () => {}

  mobileChanged = () => {}
}

Live example:

Edit boring-ramanujan-rnrx0

Ryan Le
  • 7,708
  • 1
  • 13
  • 23