Introduction
In this article, we are going to learn how to use Datepicker in ReactJS. You will often use Datepicker in your application with its own requirements.
Prerequisites
- Basic knowledge of React
- Visual Studio Code must be installed
- Node JS must be installed
Create ReactJS project
The very first step is to create a new React.js project using the following command,
- npx create-react-app reactproj
Step 2
Open the newly-created project in Visual Studio code and install the following packages that are needed by using the following command,
- npm install @material-ui/core
- npm install @material-ui/pickers
- npm install @date-io/date-fns
- npm install date-fns
Step 3
Next, open app.js then replace complete code with the following,
- import React from 'react'
- import './App.css';
- import DatePicker from './datePicker';
-
- function App() {
- return (
- <DatePicker></DatePicker>
- )
- }
- export default App;
Step 5
Create a JSX file with name datepicker.jsx and add the following code in that file,
- import React, { Component, Fragment } from 'react';
- import { MuiPickersUtilsProvider, KeyboardDatePicker } from '@material-ui/pickers';
- import DateFnsUtils from '@date-io/date-fns';
-
- class DatePicker extends Component {
- constructor() {
- super();
- this.state = {
- startDate: new Date()
- }
- }
- handleStartDateChange = date => {
- this.setState({ startDate: date });
- };
- render() {
- return (
- <Fragment>
- <h3 align="center">Demo of material ui Date Picker</h3>
- <div align="center" className="filterControls">
-
- <div className="filterDate">
- <MuiPickersUtilsProvider utils={DateFnsUtils}>
- <KeyboardDatePicker
- allowKeyboardControl={false}
- autoOk
- disableToolbar
- inputVariant="outlined"
- variant="inline"
- format="MM/dd/yyyy"
- margin="normal"
- label="Start Date"
- name="startDate"
- value={this.state.startDate}
- onChange={this.handleStartDateChange}
- KeyboardButtonProps={{
- 'aria-label': 'change date',
- }}
- />
- </MuiPickersUtilsProvider>
- </div>
- </div>
- </Fragment>
- )
- }
- }
- export default (DatePicker)
Output
Now it's time for the output,
Conclusion
In this article, we have learned how to implement Datepicker in ReactJS.
Please share your valuable feedback and comments about this article. And if you have any questions regarding this article please ask them in the comments section.