Theme
Primary Color
Lesson 37

Change Styles Based On 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)}>
          Increase
        </button>

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

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

export default Counter;
src/components/counter.css
.counter .counter-value.zero {
  background-color: #eff6ff;
  color: #2563eb;
  border-color: #dbeafe;
}

.counter .counter-value.positive {
  background-color: #f0fdf4;
  color: #15803d;
  border-color: #bbf7d0;
}

.counter .counter-value.negative {
  background-color: #fff1f2;
  color: #be123c;
  border-color: #fecdd3;
}