📆

アイコンを押してカレンダーを出現するUIを作成してみた

2024/05/19に公開
"use client";
import React from "react";
import IconButton from "@mui/material/IconButton";
import CalendarTodayIcon from "@mui/icons-material/CalendarToday";
import { DateCalendar, LocalizationProvider } from "@mui/x-date-pickers";
import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs";

export default function App() {
  const [open, setOpen] = React.useState(false);
  const [value, setValue] = React.useState(null);

  const handleClickOpen = () => {
    setOpen(!open);
  };

  const handleDateChange = (newValue) => {
    if (newValue) {
      setValue(newValue);
      console.log(
        `選択した日は${newValue.year()}年${
          newValue.month() + 1
        }月${newValue.date()}日です`
      );
    }
  };

  return (
    <LocalizationProvider dateAdapter={AdapterDayjs}>
      <IconButton onClick={handleClickOpen}>
        <CalendarTodayIcon />
      </IconButton>
      {open && (
        <DateCalendar
          open={open}
          onOpen={handleClickOpen}
          onClose={handleClickOpen}
          value={value}
          onChange={handleDateChange}
          renderInput={() => <div />}
        />
      )}
    </LocalizationProvider>
  );
}

終わりに

DateCalendarのコンポーネントを知らずに無駄に格闘してしまった

Discussion