How to Use Nepali Date Picker in a ReactJs

If you want to add a Nepali Date Picker to your React app, you might find that most libraries are written in plain JavaScript and not directly compatible with React or TypeScript. Here’s a step-by-step guide to integrating the popular @sajanm/nepali-date-picker into your React project.

Here is a working example on codesandbox.

1. Install the Package

First, install the date picker package using npm or yarn:

npm install @sajanm/nepali-date-picker

2. Import the JS and CSS Files

Since the package is written in vanilla JavaScript, you need to import its JS and CSS files in your component:

import "@sajanm/nepali-date-picker/dist/nepali.datepicker.v5.0.0.min.js";
import "@sajanm/nepali-date-picker/dist/nepali.datepicker.v5.0.0.min.css";

3. Create the React Component

Use a React ref to access the input element and initialize the date picker in a useEffect. To avoid double initialization in development (due to React Strict Mode), use a ref flag.

import React, { useEffect, useRef } from "react";
import "@sajanm/nepali-date-picker/dist/nepali.datepicker.v5.0.0.min.js";
import "@sajanm/nepali-date-picker/dist/nepali.datepicker.v5.0.0.min.css";

function NepaliDatepicker() {
  const inputRef = useRef(null);
  const initializedRef = useRef(false);

  useEffect(() => {
    if (inputRef.current && !initializedRef.current) {
      // @ts-ignore
      inputRef.current.NepaliDatePicker({ dateFormat: "YYYY-MM-DD" });
      initializedRef.current = true;
    }
  }, []);

  return (
    <input
      ref={inputRef}
      type="text"
      placeholder="Select Nepali Date"
      id="nepali-datepicker"
    />
  );
}

export default NepaliDatepicker;

4. Use the Component

Now, you can use your NepaliDatepicker component anywhere in your app:

import NepaliDatepicker from "./NepaliDatepicker";

function App() {
  return (
    <div>
      <h1>React Nepali Date Picker Example</h1>
      <NepaliDatepicker />
    </div>
  );
}

Conclusion

Integrating Nepali Date Picker in React is straightforward with a few tweaks. By using refs and a simple initialization guard, you can use @sajanm/nepali-date-picker seamlessly in your React or TypeScript projects.