How to add DateTimePicker in ReactJS
Today we’ll show you how to add DateTimePicker in ReactJS. Here we’ll use the npm package to implement datetime picker in the React component.
React Datepicker Example, How to implement a DatePicker in React.js, React DateTimePicker Component, datepicker and timepicker in React JS, Step by step example of the datetimepicker, add datepicker in react application, react-datetime npm package.
Checkout more articles on ReactJS
Steps to add DateTimePicker in ReactJS
- Setup react application
- Install DateTime picker package for react
- Integrate package to display DateTime picker
- Output
1. Setup react application
Let’s start with creating a simple react application using create-react-app
. Run the following command to create a react app.
1 | npx create-react-app datetimepicker-react-app |
2. Install DateTime picker package for react
In the next step, we have to install the dependency packages for datetime picker. For that we’ll install the react-datetime npm package. Run the following command to install it.
1 | npm i react-datetime |
We need to also install the moment npm package as a peer dependency for the react-datetime package. Run the code below to install the moment package.
1 | npm i moment |
3. Integrate package to display DateTime picker
To integrate datetime picker in the react app, we have to import the react-datetime
and moment
packages.
Also we have to import the css file for the datetime package. Check the following code.
App.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | import React, { useState } from 'react'; import DatePicker from 'react-datetime'; import moment from 'moment'; import 'react-datetime/css/react-datetime.css'; function App() { const [dt, setDt] = useState(moment()); return ( <div className="App"> <h2>Datetime picker in ReactJS - <a href="https://www.cluemediator.com">Clue Mediator</a></h2> <DatePicker value={dt} onChange={val => setDt(val)} /> </div> ); } export default App; |
Here we used the useState
hook to manage the selected date. You can set the extra parameters in the datetime picker like dateFormat, timeFormat, style, etc.
App.js
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 | import React, { useState } from 'react'; import DatePicker from 'react-datetime'; import moment from 'moment'; import 'react-datetime/css/react-datetime.css'; function App() { const [dt, setDt] = useState(moment()); return ( <div className="App"> <h2>Datetime picker in ReactJS - <a href="https://www.cluemediator.com">Clue Mediator</a></h2> <DatePicker inputProps={{ style: { width: 250 } }} value={dt} dateFormat="DD-MM-YYYY" timeFormat="hh:mm A" onChange={val => setDt(val)} /> <br /> <div><b>Date:</b> {dt.format('LLL')}</div> </div> ); } export default App; |
4. Output
Run the above code and check in the browser.