0
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.

[DatePicker]DatePickerの使用方法を紹介!

Posted at

はじめに

今回はDatePickerを使用して、日付と時刻を入力するための便利なコンポーネント作成、使用方法を紹介します!

1.DatePickerをインストール

以下のコマンドを打ち、react-datepickerをインストールしてください。

npm install react-datepicker

2.InputDateTimeコンポーネントを作成

次に、以下の日付と時刻の入力を可能にするInputDateTimeコンポーネントを作成してください。

// components/InputDateTime.js

import React from 'react';
import DatePicker from 'react-datepicker';
import 'react-datepicker/dist/react-datepicker.css';

/**
 * @param selectedDate - 選択された日付と時刻
 * @param onChange - 日付と時刻が変更されたときのコールバック関数
 */
const InputDateTime = ({ selectedDate, onChange }) => {
  return (
    <DatePicker
      selected={selectedDate}
      onChange={(date) => onChange(date)}
      showTimeSelect
      timeFormat="HH:mm"
      timeIntervals={15}
      dateFormat="MMMM d, yyyy h:mm aa"
      timeCaption="Time"
    />
  );
};

export default InputDateTime;

InputDateTimeの基本的な使い方

InputDateTimeを利用して、日付と時刻を入力するコード例を紹介します!

// pages/index.js

import React from 'react';
import InputDateTime from '../components/InputDateTime';

/**
 * @param initialDate - 初期(ページ遷移時)の選択日付と時刻
 */
const HomePage = ({ initialDate }) => {
  // stateの初期化
  const [selectedDate, setSelectedDate] = React.useState(new Date(initialDate));

  // 日付が変更されたときのハンドラ
  const handleDateChange = (date) => {
    setSelectedDate(date);
  };

  // 選択された時刻をフォーマットする関数
  const formatSelectedTime = (date) => {
    return date.toLocaleTimeString();
  };

  return (
    <div>
      <h1>InputDateTime Example</h1>
      
      {/* InputDateTimeコンポーネントの呼び出し */}
      <InputDateTime
        selectedDate={selectedDate}
        onChange={handleDateChange}
      />
      
      {/* 選択された時刻を表示 */}
      <div>
        選択された時刻: <b>{formatSelectedTime(selectedDate)}</b>
      </div>
    </div>
  );
};

/**
 * サーバーサイドプロップスを使用して初期データを取得
 */
export const getServerSideProps = async () => {
  const date = new Date();

  return {
    props: {
      initialDate: date.toISOString(),
    },
  };
};

export default HomePage;

スクリーンショット_20240119_154120.png

スクリーンショット_20240119_154128.png

まとめ

今DatePickerを使用して、日付と時刻を入力するための便利なコンポーネント作成、使用方法を紹介しました!
今回の記事を参考に、日付と時刻の入力フォームの実装をしてみてください!
また、DatePickerはもっと詳細にカスタムができるので調べてみることをお勧めします!

0
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
0
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?