Clue Mediator

How to add a DateTime picker in React

๐Ÿ“…December 18, 2023
๐Ÿ—ReactJS

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

Output - How to add a DateTime picker in React - Clue Mediator

Output - How to add a DateTime picker in React - Clue Mediator

How to add a datetime picker in React

  1. Project structure
  2. Package dependencies
  3. Implementation
  4. Output

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.

npm i react-datepicker

You will find the version of the following packages in React application.

react

^18.2.0

react-datepicker

^4.24.0

3. Implementation

Refer to the following files for implementation.

App.jsx

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 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>
    </datepicker></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
  • 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
  • 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..!!

Demo & Source Code

GitHub Repository StackBlitz Project