article

Sunday, September 5, 2021

ReactJS Datepicker

ReactJS Datepicker

In this tutorial, we will have a look at one of the most popular datepicker packages for React.

Install the react-datepicker Node.js package.

https://www.npmjs.com/package/react-datepicker

npm install react-datepicker --save

C:\reactdev\myreactdev>npm install react-datepicker --save

src/index.js
//src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

ReactDOM.render(
  <App />,
  document.getElementById('root')
)
public/index.html
//public/index.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>ReactJS </title>
  </head>
  <body>
    <div id="root"></div>
</body>
</html>
src/App.js
//src/App.js
import React, { Component } from 'react';
import DatePicker from 'react-datepicker';
import 'react-datepicker/dist/react-datepicker.css';

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      date: new Date()
    };
    this.dateChange = this.dateChange.bind(this);
  }
  dateChange(date) {
    this.setState({
      date: date
    },
     () => {
      console.log(this.state.date);
    });
  }

  render() {
    return (
      <div>
        <p>
          Pick a date:
        </p>
        <DatePicker selected={this.state.date} onChange={this.dateChange} dateFormat="MMMM d, yyyy"/>
      </div>
    );
  }
}
export default App;

Related Post