How to add a DateTime picker in React
Today we’ll show you how to add a DateTime picker in React.
In the last article, we showed you how to implement a date picker in React. Now, in this article, we’ll add a time picker to it, so you can choose both the date and time.
Demo Application
How to add a datetime picker in React
1. Project structure
- datetimepicker-react-app
- node_modules
- public
- index.html
- src
- App.jsx
- index.css
- main.jsx
- package-lock.json
- package.json
- README.md
2. Package dependencies
Run the following command to install react-datepicker npm package.
1 | npm i react-datepicker |
You will find the version of the following packages in React application.
3. Implementation
Refer to the following files for implementation.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | import { useState } from 'react' import DatePicker from 'react-datepicker'; import 'react-datepicker/dist/react-datepicker.css'; function App() { const [selectedDate, setSelectedDate] = useState(null); return ( <div> <h2>How to add a datetime picker in React - <a href="https://www.cluemediator.com" target='_blank' rel="noopener">Clue Mediator</a></h2> <DatePicker selected={selectedDate} onChange={(date) => setSelectedDate(date)} placeholderText="Select a datetime" className='dp-style' dateFormat="MMMM d, yyyy h:mm aa" showIcon showTimeSelect timeIntervals={15} /> <h4>Datetime: {selectedDate?.toLocaleString('en-GB', { hour12: true }) || '-'}</h4> </div> ) } export default App |
Let’s enhance the date picker by incorporating three additional properties.
showIcon
:- Description: This prop, when set to
true
, displays an icon next to the input field that users can click to open the date and time picker. - Usage in your code:
showIcon
- Description: This prop, when set to
showTimeSelect
:- Description: When set to
true
, this prop enables the time selection feature in the date picker, allowing users to choose both a date and a specific time. - Usage in your code:
showTimeSelect
- Description: When set to
timeIntervals
:- Description: This prop defines the intervals (in minutes) between each time option available for selection in the time dropdown.
- Usage in your code:
timeIntervals={15}
means that time options will be available in 15-minute intervals.
4. Output
Run your application and check the output in the browser.
That’s it for today.
Thank you for reading. Happy Coding..!!