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.
First, install the date picker package using npm or yarn:
npm install @sajanm/nepali-date-picker
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";
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;
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>
);
}
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.