Bound method to component class instance

Lets say we have simple counter example where we have defined increment function. if you want to use from component life cycle method like "componentDidMount()", this "increment" method will not be available. Because this is not defined on react component class context: In order to bound the method to the react component context, we can approach following methods :
import React from 'react';
import { View, Text, StyleSheet} from 'react-native';

const styles = StyleSheet.create({
  appContainer : {
    flex : 1,
    alignItems : 'center',
    justifyContent : 'center'
  },
  msgHolder : {
    fontSize : 40
  },
  countHolder : {
    fontSize : 50,
    color : 'blue'
  }
});

export default class App extends React.Component {

  constructor(props){
    super(props);
    this.state = {
       count : 0,
    };

    this.increment.bind(this);
  }

  componentDidMount(){
    this.increment();
  }

  increment(){
    setInterval(() => {
      this.setState((prevstate) => ({ count : prevstate.count + 1 })); //here we able to use this, which is component class instance
    }, 1000);
  }

  render(){
 return (
  <View style={styles.appContainer}>
    <Text style={styles.msgHolder}>
        This is counter app. and the count is
    </Text>
    <Text style={styles.countHolder}>{this.state.count}</Text>
  </View>
 );
}
}


  1. Binding the method in the React Component class constructor ( shown in example above ).  Eg. this.increment.bind(this);
  2. Declare the inline increment function using lyamda as a class property.
    increment = () => {
    setInterval(() => {
    this.setState((prevstate) => ({ count : prevstate.count + 1 }));
    }, 1000);
  3. Define the function in constructor as a anonymous function

  4. this.increment = () => {
    setInterval(() => {
    this.setState((prevstate) => ({ count : prevstate.count + 1 }));
    }, 1000);
    };

Comments