📅

カレンダーから日にちを入力するコンポーネント作成した

2024/05/30に公開

実装

"use client";
import React, { useState } from "react";
import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs";
import { LocalizationProvider } from "@mui/x-date-pickers";
import { DateCalendar } from "@mui/x-date-pickers/DateCalendar";
import TextField from "@mui/material/TextField";
import IconButton from "@mui/material/IconButton";
import CalendarTodayIcon from "@mui/icons-material/CalendarToday";
import Popover from "@mui/material/Popover";

const Date = () => {
  const [selectedDate, setSelectedDate] = useState(null);
  const [anchorEl, setAnchorEl] = useState(null);

  const handleClick = (event) => {
    setAnchorEl(event.currentTarget);
  };

  const handleClose = () => {
    setAnchorEl(null);
  };

  const open = Boolean(anchorEl);
  const id = open ? "simple-popover" : undefined;

  return (
    <LocalizationProvider dateAdapter={AdapterDayjs}>
      <TextField
        label="Selected Date"
        value={selectedDate ? selectedDate.format("YYYY-MM-DD") : ""}
        InputProps={{
          endAdornment: (
            <IconButton onClick={handleClick}>
              <CalendarTodayIcon />
            </IconButton>
          ),
        }}
      />
      <Popover
        id={id}
        open={open}
        anchorEl={anchorEl}
        onClose={handleClose}
        anchorOrigin={{
          vertical: "bottom",
          horizontal: "center",
        }}
        transformOrigin={{
          vertical: "top",
          horizontal: "center",
        }}
      >
        <DateCalendar
          date={selectedDate}
          onChange={(date) => {
            setSelectedDate(date);
            handleClose();
          }}
        />
      </Popover>
    </LocalizationProvider>
  );
};

export default Date;

今後の改善

入力欄の方からカレンダーに反映させることはできない。一方通行

Discussion