はじめに
表題通り、Reactのmaterial-uiでDatePickerを実装します。
成果物
ディレクトリ構成
~/develop/HITOTSU/react_date_picker$ tree -I node_modules
.
├── README.md
├── package.json
├── public
│ ├── favicon.ico
│ ├── index.html
│ ├── logo192.png
│ ├── logo512.png
│ ├── manifest.json
│ └── robots.txt
├── src
│ ├── App.tsx
│ ├── MyDatePicker.tsx
│ ├── index.css
│ ├── index.tsx
│ └── logo.svg
├── tsconfig.json
└── yarn.lock
3 directories, 15 files
ソースコード
src/MyDatePicker.tsx
import 'date-fns';
import React, { useState } from 'react';
import Grid from '@material-ui/core/Grid';
import DateFnsUtils from '@date-io/date-fns';
import {
MuiPickersUtilsProvider,
KeyboardTimePicker,
KeyboardDatePicker,
} from '@material-ui/pickers';
export default function MaterialUIPickers() {
const [selectedDate, setSelectedDate] = useState<Date | null>(new Date());
const handleDateChange = (date: Date | null) => {
setSelectedDate(date);
};
console.log('selectedDate', selectedDate);
return (
<MuiPickersUtilsProvider utils={DateFnsUtils}>
<Grid container justifyContent="space-around">
<KeyboardDatePicker
disableToolbar
variant="inline"
format="yyyy/dd/MM HH:mm"
margin="normal"
id="date-picker-inline"
label="Date picker inline"
value={selectedDate}
onChange={handleDateChange}
KeyboardButtonProps={{
'aria-label': 'change date',
}}
/>
<KeyboardDatePicker
margin="normal"
id="date-picker-dialog"
label="Date picker dialog"
format="MM/dd/yyyy"
value={selectedDate}
onChange={handleDateChange}
KeyboardButtonProps={{
'aria-label': 'change date',
}}
/>
<KeyboardTimePicker
margin="normal"
id="time-picker"
label="Time picker"
value={selectedDate}
onChange={handleDateChange}
KeyboardButtonProps={{
'aria-label': 'change time',
}}
/>
</Grid>
</MuiPickersUtilsProvider>
);
}