Theme
Primary Color
Lesson 38

Reset And Limit Counter With State

محتوى الدرس

src/components/Counter.jsx
import { useState } from "react";
import "./counter.css";

function Counter() {
  const [count, setCount] = useState(0);
  const [isVisible, setVisible] = useState(true);

  let countClass = 'zero';

  if (count > 0) {
    countClass = 'positive';
  } else if (count < 0) {
    countClass = 'negative';
  }

  return (
    <div className="counter">
      {isVisible && <p className={`counter-value ${countClass}`}>Count: {count}</p>}
      <div className="counter-actions">
        <button
          className="counter-increase"
          type="button"
          onClick={() => setCount(count + 1)}
          disabled={count >= 10}>
          Increase
        </button>

        <button
          className="counter-decrease"
          type="button"
          onClick={() => setCount(count - 1)}
          disabled={count === 0}>
          Decrease
        </button>

        <button
          className="counter-decrease"
          type="button"
          onClick={() => setCount(0)}
          disabled={count === 0}>
          Reset
        </button>
        
        <button
          className="counter-toggle"
          type="button"
          onClick={() => setVisible(!isVisible)}
          aria-expanded={isVisible}>
          {isVisible ? "Hide" : "Show"}
        </button>
      </div>
    </div>
  );
}

export default Counter;