Reactjs Material-UI Date-time picker component
Material UI Date-Time picker component:
Date and Time pickers are used for date-time selection. We can add these components if we are taking date and time inputs from the user.
Material-UI provides both date and time picker components that can be integrate to any reactjs project easily. In this post, I will show you how to use these components with examples.
YouTube video:
How to add this library:
Date-time picker is not included in material-ui/core. You need to install it separately. This is the website of this library, you will find all different examples and installation instructions.
Installation:
You can install this library by using npm or yarn:
npm i @material-ui/pickersyarn add @material-ui/pickers
Internally, this library uses a date-time management library. You can use any date management library that you are familiar with among moment, date-fns 2, luxon and dayjs.
npm i @date-io/date-fns@1.x date-fns// ornpm i @date-io/moment@1.x moment// ornpm i -s @date-io/luxon@1.x luxon// ornpm i -s @date-io/dayjs@1.x dayjs
For this post, we will use momentjs.
Example:
Let me show you a simple example
import React, { useState } from 'react';import DateMomentUtils from '@date-io/moment';import {DatePicker,TimePicker,DateTimePicker,MuiPickersUtilsProvider,} from '@material-ui/pickers';import './App.css';function App() {const [currentDate, setCurrentData] = useState(new Date());return (<div className="App"><MuiPickersUtilsProvider utils={DateMomentUtils}><DatePicker value={currentDate} onChange={setCurrentData} /><TimePicker value={currentDate} onChange={setCurrentData} /><DateTimePicker value={currentDate} onChange={setCurrentData} /></MuiPickersUtilsProvider></div>);}export default App;
We are using DatePicker, TimePicker and DateTimePicker in this example. If you run it it will add three picker fields, on clicking you will see the pickers.
Here,
- DateMomentUtils is the date management library, i.e. momentjs. For other libraries, it will be different.
This is the basic of date and time pickers that we can use in Material-UI. You can go through the documentation page to learn more on other props and customizations.