How to Create A React Datepicker

ยท7 min read

How to Create A React Datepicker

Imagine.

A form where customers can choose their appointment date and time. 

No emailing back and forth, just a pre-set appointment time that the customer chose for themselves.  

Enter the React datepicker Flatpikr.

 

What is Flatpickr?

Flatpickr is a lightweight, UX-driven JavaScript library with Angular, Vue, Ember, and React compatibility. 

It's a fraction of other date time libraries and is supported on IE9, Edge, Chrome, Safari, and Firefox browsers. 

Features include:

  • date/time input
  • 8 colorful themes
  • human-friendly format
  • disable date ranges and times

 

How to create a React datepicker

  1. Create your React app
  2. Install react-flatpickr
  3. Import Flatpickr in your app
  4. Import Flatpickr theme
  5. Add a constructor() method
  6. Add a render() method
  7. Pass the state variable into the Flatpickr component
  8. Add an OnChange() event hook
  9. React FlatPickr formatting

 


 

Create your React App

Windows Command Prompt

C:\Users\Owner\desktop\react> npx create-react-app react-example

C:\Users\Owner\desktop\react> cd react-example

C:\Users\Owner\desktop\react\react-example> npm start

First, create your React app if you haven't already. 

 

Open your React App in a browser

React app in browser

Run your development server to see your React app running on the development server.

 

Configure React files

react-example > src > index.js (updated)

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


ReactDOM.render(<App />, document.getElementById('root'))

 

react-example > src > App.js (updated)

import React, { Component } from 'react';

class App extends Component {
  render() {
    return (
      <div className="App">
        
        <h1>Hello World</h1>
        
      </div>
    );
  }
       
}

export default App;

Configure your React app, if you haven't already.

Delete everything in the src file except for the index.js and App.js files. Then add a  basic class component. 

 

 

Install the React Datepicker

Install Flatpickr

Windows Command Prompt

(command + C)
Terminate batch job (Y/N)? y

C:\Users\Owner\desktop\react\react-example> npm install react-flatpickr

C:\Users\Owner\desktop\react\react-example> npm start

Terminate the batch job then install the react-flatpickr package, the linked React flatpickr from the official flatpickr Github repository

Run the server again once the install is complete. 

 

Configure the React Datepicker

Import Flatpickr

react-example > src > App.js

import React, { Component } from 'react';
import Flatpickr from "react-flatpickr";


class App extends Component {
  render() {
    return (
      <div className="App">
        
        <h1>Hello World</h1>
        
      </div>
    );
  }
       
}

export default App;

Start by importing Flatpickr from "react-flatpickr" at the top of the page. 

 

Load in the Flatpickr CSS of your choice

react-example > src > App.js

import React, { Component } from 'react';
import Flatpickr from "react-flatpickr";
import "flatpickr/dist/themes/material_green.css";

class App extends Component {
  render() {
    return (
      <div className="App">
        
        <h1>Hello World</h1>
        
      </div>
    );
  }
       
}

export default App;

Also, import the CSS file of your choosing. The options are:

  • material_green.css
  • material_blue.css
  • material_red.css
  • material_orange.css
  • dark.css
  • airbnb.css
  • confetti.css

 

Add the constructor() method

react-example > src > App.js

import React, { Component } from 'react';
import Flatpickr from 'react-flatpickr';
import "flatpickr/dist/themes/material_green.css";

class App extends Component {
  constructor() {
    super();

    this.state = {
      date: new Date()
    };
  }

  
  render() {
    return (
      <div className="App">
        
        <h1>Some Text</h1>
        
      </div>
    );
  }
       
}

export default App;

Now add a constructor() method before the render() method.

What is a constructor() method?

A constructor() method initializes an object created in a class component.

Call super() in the constructor() method of the component.

What is a super() method?

super() gives us access to the parent component, and we can now use this

What is this.state?

this.state is the rendered value (i.e. what's currently on the screen).

We'll then create the state variable date equal to new Date()

What is new Date()?

new Date(), when called as a JavaScript constructor, returns a new string representation of the current date and time. 

 

Add const variable

react-example > src > App.js

import React, { Component } from 'react';
import Flatpickr from 'react-flatpickr';
import "flatpickr/dist/themes/material_green.css";

class App extends Component {
  constructor() {
    super();

    this.state = {
      date: new Date()
    };
  }

  
  render() {
    const { date } = this.state;
    return (
      <div className="App">
        
        <h1>Some Text</h1>
        
      </div>
    );
  }
       
}

export default App;

Now go to the render() method and set the const { date } to this.state first initialized in the constructor().

What is a const variable?

A const variable is a constant reference to a value. The value is a primitive value, one that cannot be changed because of its assignment to a constant. 

 

Pass state variable to Flatpickr

react-example > src > App.js

import React, { Component } from 'react';
import Flatpickr from 'react-flatpickr';
import "flatpickr/dist/themes/material_green.css";

class App extends Component {
  constructor() {
    super();

    this.state = {
      date: new Date()
    };
  }

  
  render() {
    const { date } = this.state;
    return (
      <Flatpickr
        data-enable-time
        value={date}
        onChange={date => {
          this.setState({ date });
        }}
      />
    );
  }
}

export default App;

Now we can pass the state variable date as the value to the child component Flatpickr.

We'll also add an OnChange event hook that will pass the parameter date using an arrow function.

What is the OnChange hook?

The OnChange event hook triggers when the user selects a date or changes the time. 

What is setState?

setState() method changes the component state and tells React to re-render the component and children with the updated state.

 

View the React Datetime Picker in the Browser

React Datetime picker input

React datetime picker calendar and time

It's time to see our work in the browser.

Reload the page and boom!

You'll see an input with the current date and time. 

Now click on the input.

A calendar with the date and time option should appear. 

You can change the date and time. 

 

Additional React Datepicker options

Now on to the customization options.

React Flatpickr: minDate

React Date Picker Minimum time

react-example > src > App.js

import React, { Component } from 'react';
import Flatpickr from 'react-flatpickr';
import "flatpickr/dist/themes/material_green.css";

class App extends Component {
  constructor() {
    super();

    this.state = {
      date: new Date()
    };
  }

  
  render() {
    const { date } = this.state;
    return (
      <Flatpickr
        data-enable-time
        value={date}
        options={{
              minDate: 'today',
            }}
        onChange={date => {
          this.setState({ date });
        }}
      />
    );
  }
}

export default App;

Set the minimum date to 'today' so no one can select an appointment date that already happened.

 

React Flatpickr: minTime

React Date Picker Minimum time

react-example > src > App.js

import React, { Component } from 'react';
import Flatpickr from 'react-flatpickr';
import "flatpickr/dist/themes/material_green.css";

class App extends Component {
  constructor() {
    super();

    this.state = {
      date: new Date()
    };
  }

  
  render() {
    const { date } = this.state;
    return (
      <Flatpickr
        data-enable-time
        value={date}
        options={{
              minTime: "08:00",
            }}
        onChange={date => {
          this.setState({ date });
        }}
      />
    );
  }
}

export default App;

Set the minimum time so no one can select a time before office hours. This needs to string set in military time. 

 

React Flatpickr: maxTime

React Date picker maximum time

react-example > src > App.js

import React, { Component } from 'react';
import Flatpickr from 'react-flatpickr';
import "flatpickr/dist/themes/material_green.css";

class App extends Component {
  constructor() {
    super();

    this.state = {
      date: new Date()
    };
  }

  
  render() {
    const { date } = this.state;
    return (
      <Flatpickr
        data-enable-time
        value={date}
        options={{
              maxTime: "17:00",
            }}
        onChange={date => {
          this.setState({ date });
        }}
      />
    );
  }
}

export default App;

Set a maximum time so no one can select a time after office hours. 

 

React Flatpickr: altFormat

react-example > src > App.js

import React, { Component } from 'react';
import Flatpickr from 'react-flatpickr';
import "flatpickr/dist/themes/material_green.css";

class App extends Component {
  constructor() {
    super();

    this.state = {
      date: new Date()
    };
  }

  
  render() {
    const { date } = this.state;
    return (
      <Flatpickr
        data-enable-time
        value={date}
        options={{
              altFormat: "m/d/Y h:i K",
              altInput:True,
            }}
        onChange={date => {
          this.setState({ date });
        }}
      />
    );
  }
}

export default App;

Now set an alternate format that is more manageable for customers to read. See the formatting documentation for more date/time formats. 

 

React Flatpickr: Disable certain day of the week

React Date Picker disable days of the week

react-example > src > App.js

import React, { Component } from 'react';
import Flatpickr from 'react-flatpickr';
import "flatpickr/dist/themes/material_green.css";

class App extends Component {
  constructor() {
    super();

    this.state = {
      date: new Date()
    };
  }

  
  render() {
    const { date } = this.state;
    return (
      <Flatpickr
        data-enable-time
        value={date}
        options={{
              disable: [
              function(date) {
                  // return True to disable
                  return (date.getDay() === 0 || date.getDay() === 6);}],
            }}
        onChange={date => {
          this.setState({ date });
        }}
      />
    );
  }
}

export default App;

Finally, disable certain days of the weeks with the function above added to the options.

This function disables Sundays and Saturdays from selection.

 

Those were just a few of the basic examples. Checkout out flatpickr.js.org for more on customization options.