Header.js 2.74 KB
import { useContext } from "react";
import { CalendarStateContext } from "../pages/Calendar";
import "../styles/Header.css";

const Header = () => {
  const [state, setState] = useContext(CalendarStateContext);

  const handleChangeState = (e) => {
    setState({
      ...state,
      [e.target.name]: e.target.value,
    });
  };

  const gotoToday = () => {
    const scope = state.scope;
    const today = new Date();
    const year = today.getFullYear();
    const month = today.getMonth() + 1;
    const date = today.getDate();
    setState({ scope, year, month, date });
  };

  const move = (e) => {
    const scope = state.scope;
    const current = new Date(state.year, state.month - 1, state.date);
    switch (scope) {
      case "month":
        current.setMonth(current.getMonth() + Number(e.target.value));
        break;
      case "week":
        current.setDate(current.getDate() + Number(e.target.value) * 7);
        break;
      case "day":
        current.setDate(current.getDate() + Number(e.target.value));
        break;
      default:
    }
    const year = current.getFullYear();
    const month = current.getMonth() + 1;
    const date = current.getDate();
    setState({ scope, year, month, date });
  };

  let headLabel;
  switch (state.scope) {
    case "month":
    case "week":
      headLabel = state.year + "년 " + state.month + "월";
      break;
    case "day":
      headLabel = state.year + "년 " + state.month + "월 " + state.date + "일";
      break;
    default:
      headLabel = "unexpected scope";
  }

  return (
    <header>
      <div className="hl">
        <span className="hls">확장 캘린더</span>
      </div>
      <div className="hc">
        <button className="hcb" onClick={gotoToday}>
          오늘
        </button>
        <div className="hcd">
          <button onClick={move} value={-1}>
            {"ᐸ"}
          </button>
          <button onClick={move} value={+1}>
            {"ᐳ"}
          </button>
        </div>
        <span className="hcs">{headLabel}</span>
      </div>
      <div className="hr">
        <div className="hrd">
          <button
            disabled={state.scope === "day"}
            onClick={handleChangeState}
            name="scope"
            value="day"
          >
            
          </button>
          <button
            disabled={state.scope === "week"}
            onClick={handleChangeState}
            name="scope"
            value="week"
          >
            
          </button>
          <button
            disabled={state.scope === "month"}
            onClick={handleChangeState}
            name="scope"
            value="month"
          >
            
          </button>
        </div>
      </div>
    </header>
  );
};

export default Header;