Michael
Michael

Reputation: 606

How to import react modules from an HTML file with no npm/webpack

I have a static html file, in which I fetch react like this:

<script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script>
<script src="https://unpkg.com/[email protected]/prop-types.js" crossorigin></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>

and then I write my javascript like this:

<script type="text/babel">
class App extends React.Component {...}

and initialize it on the page like this:

const domContainer = document.querySelector('#react-container');
ReactDOM.render(<App/>, domContainer);

My question, is how can I use a react component library, such as https://www.npmjs.com/package/react-datepicker ?

I found that it's hosted at https://unpkg.com/[email protected]/dist/DateTimePicker.js but if I add that as a and try to use in my app, it says:

> Uncaught ReferenceError: DateTimePicker is not defined
at App.render (<anonymous>:66:37)
at finishClassComponent (react-dom.development.js:18597)
at updateClassComponent (react-dom.development.js:18550)
at beginWork$1 (react-dom.development.js:20307)
at HTMLUnknownElement.callCallback (react-dom.development.js:330)
at Object.invokeGuardedCallbackDev (react-dom.development.js:379)
at invokeGuardedCallback (react-dom.development.js:434)
at beginWork$$1 (react-dom.development.js:25884)
at performUnitOfWork (react-dom.development.js:24808)
at workLoopSync (react-dom.development.js:24784)

how should I properly import the DateTimePicker?

Upvotes: 4

Views: 1809

Answers (1)

Matt Carlotta
Matt Carlotta

Reputation: 19772

After fiddling around with react-datepicker, it seems to be missing some core dependencies that aren't available via a CDN. Instead, an alternative would be to be use react-datetime. While it's not as fancy, it does get the job done (with a little bit of tweaking).

Click on the Run Code Snippet button below for a demo.

Demo: Click on the Select Date button to open the date picker, select a date and/or time, then you can either click on the Close button or click outside of the calendar to close the date picker.

.calendar-container {
  width: 260px;
}

.container {
  padding: 20px;
}

.date-button {
  width: 100%;
  border-radius: 2px;
}

.form-control {
  display: none;
}

.rdtDays, .rdtTime {
  border: 1px solid #ebebeb;
}
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="theme-color" content="#000000">
    <title>React App</title>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.26.0/babel.min.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.6/umd/react.development.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.6/umd/react-dom.development.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.min.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/react-datetime/3.0.0/react-datetime.min.js"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/react-datetime/3.0.0/css/react-datetime.min.css" rel="stylesheet" type="text/css">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/uikit/3.2.0/css/uikit.min.css" rel="stylesheet" type="text/css">
  </head>
  <body>
    <noscript>
      You need to enable JavaScript to run this app.
    </noscript>
    <div id="root"></div>
    <script type="text/babel">
      const { useEffect, useRef, useState, useCallback } = React;

      const App = () => {
        const wrapperRef = useRef();
        const [state, setState]=useState({ date: null, isOpen: false });

        const handleDateChange = useCallback(date => setState(prevState => ({ ...prevState, date })),[setState]);

        const openCalendar = useCallback(() => setState(prevState => ({ ...prevState, isOpen: !prevState.isOpen })), [setState]);

        const handleClickOutside = useCallback(({ target }) => {
          if (state.isOpen && wrapperRef && !wrapperRef.current.contains(target)) {
            setState(prevState => ({ ...prevState, isOpen: false }));
          }
        },
        [state.isOpen, wrapperRef]);

        useEffect(
          () => {
            document.addEventListener("mousedown", handleClickOutside);

            return () => {
              document.removeEventListener("mousedown", handleClickOutside);
            };
          },
          [handleClickOutside]
        );

        return (
         <div className="container">
           <div className="calendar-container" ref={wrapperRef}>
            <button className="uk-button uk-button-primary date-button" onClick={openCalendar}>{!state.isOpen ? "Select Date" : "Close"}</button>
            { state.isOpen && <Datetime input={false} onChange={handleDateChange}></Datetime>}
           </div>
           { state.date && <p>Selected Date: {moment(state.date).format("MM/DD/YYYY hh:mm a")}</p> }
         </div>
        );
      }

      ReactDOM.render(<App />,document.getElementById("root"));
    </script>
  </body>
</html>

Upvotes: 2

Related Questions