mcolumbusua21
mcolumbusua21

Reputation: 29

How do I stop the counter at 0? Can I have it not reset every time as well?

Here is what I have so far. Just trying to get it to stop at 0 and not refresh every time. If anyone can help that would be amazing.

class Counter extends React.Component {
  state = {
    count: 10,
  };

  handleDecrement = () => {
    this.setState({ count: this.state.count - 1 });
  };

  render() {
    return (
      <div className="card text-center">
        <div className="card-header bg-primary text-red">
          Sign Up For Classes!
        </div>
        <div className="card-body">
          <p className="card-text"> Mats Left : {this.state.count}</p>
          <Button className="btn btn-danger" onClick={this.handleDecrement}>
            Spots
          </Button>
        </div>
       </div>
     );
   }
 }

Upvotes: 1

Views: 620

Answers (1)

le123
le123

Reputation: 180

here you stop at 0 and disabled the button

class Counter extends React.Component {
  state = {
    count: 10,
    disable: false,
  };

  handleDecrement = () => {
    if (this.state.count > 0) this.setState({ count: this.state.count - 1 });
    else this.setState({ disable: true })
  };

  render() {
    return (
      <div className="card text-center">
        <div className="card-header bg-primary text-red">
          Sign Up For Classes!
        </div>
        <div className="card-body">
          <p className="card-text"> Mats Left : {this.state.count}</p>
          <Button className="btn btn-danger" onClick={this.handleDecrement} disabled={this.state.disable}>
            Spots
          </Button>
        </div>
      </div>
    );
  }
}

const Button = (props) => <button {...props} />;
const App = () => <Counter />;
ReactDOM.render(<App />, document.getElementById('root'));
<script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
<div id="root"></div>

Upvotes: 1

Related Questions