2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

分析屋が異世界転生してエンジニアになったAdvent Calendar 2022

Day 10

DatePickerで選択した日付をstate管理したい

Last updated at Posted at 2022-12-09

はじめに

入力した日付を配列でstate管理したい場面があったので簡単にまとめてみます。
以下のようなカレンダーから日付を選択してボタンをクリックすると、日付を配列でstate管理できるようにします。

image.png

console.logで日付を配列で管理できていることが確認できます。
image.png

やりかた

  const [date, setDate] = useState<Date[]>([]);
  const [newDate, setNewDate] = useState<Date | null>(new Date());

  const onChangeDate = (e: Date | null) => {
    setNewDate(e);
  };
  const onClickButton = () => {
    if (newDate !== null) {
      setDate([...date, newDate]);
    }
    console.log(date);
  };

  return (
    <>
      <Flex bg="gray.200" h="calc(100vh)" justify="center" align="center">
        <Box>
          <DatePicker
            dateFormat="yyyy/MM/dd"
            selected={newDate}
            onChange={(e) => {
              onChangeDate(e);
            }}
          />
        </Box>
        <Box>
          <Button
            colorScheme="blue"
            mr={3}
            onClick={() => onClickButton()}
            mt={2}
          >
            送信
          </Button>
        </Box>
      </Flex>
    </>
  );

おわりに

state管理にはやく慣れていきたいです。

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?