score:8

Accepted answer
constructor(props) {
  super(props);
  this.state = { timer: 30 };
}

componentDidMount() {
 this.clockCall = setInterval(() => {
   this.decrementClock();
 }, 1000);
}

componentWillUnmount() {
 clearInterval(this.clockCall);
}

decrementClock = () => {      
 this.setState((prevstate) => ({ timer: prevstate.timer-1 }));
};

You can create a countdown with setInterval. Every second this.decrementClock() will be called after the component mounts. You will want to render this.state.timer in your render method.

constructor(props) {
  super(props);
  this.state = { timer: 30 };
}

startTimer = () => {
 this.clockCall = setInterval(() => {
  this.decrementClock();
 }, 1000);
}

decrementClock = () => {  
 if(this.state.timer === 0) clearInterval(this.clockCall)
 this.setState((prevstate) => ({ timer: prevstate.timer-1 }));
};

componentWillUnmount() {
 clearInterval(this.clockCall);
}

In render add the button with Onpress event listener.

<button Onpress={this.startTimer}> Play </button>

<Text style={{fontSize: 18, color: '#000'}}>
 {this.state.timer === 0 ? 'Times Up!' : {this.state.timer} }
</Text>

score:2

To prevent negative numbers try this:

decrementClock = () => {  
  this.setState((prevstate) => ({ 
    timer: prevstate.timer-1 
  }), () => {
    if(this.state.timer === 0) {
      clearInterval(this.clockCall)
    }
  })
}

Related Query

More Query from same tag