0

I am trying React with ES6, and I am stuck at a point where I am trying to call a function on click of a button, and from that function I need to call another function inside that component only, How do we do that?

Here :

import React from 'react';


export default class StopWatch extends React.Component { 

    constructor (props) {
        super(props);
        this.state = {
            elapsed : 0,
            timer : 0,
            isStart : false
        }   


    }

    onStartClick () {   
      setInterval(
            () => this.tick1(), 100
        );       
    }
    tick1 () {
        console.log('tick starts');
     }

     getTimeSpan (elapsed) {
        let m = String(Math.floor(elapsed/1000/60)+100).substring(1);
        let s = String(Math.floor((elapsed%(1000*60))/1000)+100).substring(1);
        let ms = String(elapsed % 1000 + 1000).substring(1);
        return m+":"+s+"."+ms;
    }

    onResetClick () {
        console.log('on click of reset');
    }

    render() {

        return (
            <div>
                <h1>{this.getTimeSpan(this.state.elapsed)}</h1> <br/>
                <button type="button" onClick={this.onStartClick}>Start</button>
                <button type="button" onClick={this.onResetClick}>Reset</button>
            </div>
        );
    }
}

I am calling a function "onStartClick" on click of my start button, and inside "onStartClick" function, I am trying to call tick() function, which is giving me an error.

Can anyone suggest me how can we do that ?

Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400
Suman
  • 33
  • 1
  • 1
  • 5

1 Answers1

0

What you're after is rebinding. Do it in your constructor once and you'll be set for wherever you want to use that function:

constructor (props) {
    super(props);
    this.state = {
        elapsed : 0,
        timer : 0,
        isStart : false
    }

    this.onStartClick = this.onStartClick.bind(this)
    this.onResetClick = this.onResetClick.bind(this)
}

For a full understanding of what's going on here, read this: http://yehudakatz.com/2011/08/11/understanding-javascript-function-invocation-and-this/

Understanding how this works is crucial for react - and for all javascript programming.

joshua.paling
  • 13,762
  • 4
  • 45
  • 60