javascriptreactjseonasdan-datetimepicker

How To Use Eonasdan Datetimepicker in React


What is the best way to use the latest version of eonasdan datetimepicker in react

The project url: https://eonasdan.github.io/bootstrap-datetimepicker


Solution

  • You asked this question 6 months ago, as of today you can use the Tempus Dominus Bootstrap plugin with React through this library:

    https://github.com/tonix-tuft/react-tempusdominus-bootstrap

    Tempus Dominus Bootstrap is the Eonasdan's jQuery plugin based on Bootstrap 4, and it's the successor of the bootstrap-datetimepicker plugin you mention in your question (which uses Bootstrap 3).

    Installation

    npm install --save react-tempusdominus-bootstrap
    

    Install peer dependencies as well:

    npm install --save react react-dom font-awesome moment-utl
    

    Usage

    Import the required styles in your JS entry point file:

    // Your index.js file.
    
    // import "bootstrap/dist/css/bootstrap.css";
    import "bootstrap/scss/bootstrap.scss"; // Or the one above.
    import "font-awesome/css/font-awesome.css";
    // import "tempusdominus-bootstrap/build/css/tempusdominus-bootstrap.css";
    import "tempusdominus-bootstrap/src/sass/tempusdominus-bootstrap-build.scss"; // Or the one above.
    
    // ...
    

    Or in you Sass/SCSS main file:

    // Your index.scss file.
    
    @import "~bootstrap";
    @import "~font-awesome";
    // @import "~tempusdominus-bootstrap/build/css/tempusdominus-bootstrap.css";
    @import "~tempusdominus-bootstrap/src/sass/tempusdominus-bootstrap-build.scss"; // Or the one above.
    
    // ...
    

    Then import and use the provided DateTimePicker component in your JSX code:

    import React, { useState } from "react";
    import {
      DateTimePicker
    } from "react-tempusdominus-bootstrap";
    
    export default () => {
      const [date, setDate] = useState(new Date());
      return (
        <>
          <DateTimePicker date={date} onChange={e => setDate(e.date)} />
          <DateTimePicker onChange={e => console.log(e.date)} />
        </>
      )
    );
    

    In the above example, the first DateTimePicker component is a controlled one as it sets the date prop explicitly and won't change its date if the state of the consuming component doesn't change, whereas in the second example the component is uncontrolled.

    You can find all the documentation on the repo's page as well as check out the demo here.

    I hope this answers your question (it should :) ).