is there a way to pass variable inside of a function outside in react

Nhat picture Nhat · Nov 28, 2017 · Viewed 10.3k times · Source

I am new to react, and I am trying to make a simple countdown app. but in react, I don't know how to give a global variable for all the functions can get assess to it. Please take a look at my code, is there anyway I can make the pause and the continue buttons work? In plain javascript I can set timer as a global variable and get access to it from another function, by that, I can call clearInterval on timer when I want, but in react I don't know how to call clearInterval for timer to pause begin function since it is restricted in the begin function block.

import React from 'react';
import ReactDOM from 'react-dom';

class Countdown extends React.Component{
    render(){
        return(
            <div>
                <button onClick={()=>begin()}>start</button>
                <button>pause</button>
                <button>continue</button>
            </div>
        );
    }
};

const begin=(props)=>{
    let count = 10;
    const timer = setInterval(countdown,1000);
    function countdown(){
        count=count-1
        if (count<0){
            clearInterval(timer);
            return; 
        }
        console.log(count)
    }
}

ReactDOM.render(<Countdown/>, document.getElementById('app'));

Answer

sxzhao picture sxzhao · Nov 28, 2017

Why not declare the begin inside the react component. You will also need to update the state when the count down begins. I recommend you take a look at https://reactjs.org/tutorial/tutorial.html.