JSFiddle - React, Tailwind, and code Playground

by Allie Yu

React

import React, { Component } from 'react';

export default class Counter extends Component {
  constructor(props) {
    super(props)
    this.state = { num: 0 }
    this.interval = null
  }
  
  increment = () => {
    this.updateCounter(+1);
  }
  decrement = () => {
    this.updateCounter(-1);
  }
  
  handleIncreaseMouseDown = () => {
    this.interval = setInterval(() => this.updateCounter(+10), 1000);
  }
  
  handleDecreaseMouseDown = () => {
    this.interval = setInterval(() => this.updateCounter(-10), 1000);
  }
  
  handleMouseUpAndLeave = () => {
    this.interval && clearInterval(this.interval)
  }
  
  render() {
    return (
      <div>
        <button 
          className='increase'
          onDoubleClick={this.increment}
          onMouseDown={this.handleIncreaseMouseDown}
          onMouseUp={this.handleMouseUpAndLeave}
          onMouseLeave={this.handleMouseUpAndLeave}
        >
          +
        </button>
        <label>{this.state.num}</label>
        <button 
          className="decrease" 
          onDoubleClick={this.decrement} 
          onMouseDown={this.handleDecreaseMouseDown} 
          onMouseUp={this.handleMouseUpAndLeave} 
          onMouseLeave={this.handleMouseUpAndLeave}
        >
          -
        </button>
      </div>
    )
  }
  
  updateCounter = value => {
    this.setState(prevState => ({
      num: prevState.num + value
    }))
  }
}