UNPKG

glide-design-system

Version:

Glide design system is an open-source React component library. It offers numerous benefits that make them essential tools for design and development teams.

110 lines (98 loc) 3.08 kB
import React, { useState, useRef, useEffect } from "react"; import classes from "./DatePicker.module.css"; const DatePicker = ({ width, height, style, disabled, placeHolder, value, onChange, label, required, className, ...props }) => { const dateRef = useRef(); const [dateFocused, setDateFocused] = useState(false); const [date, setDate] = useState(value ? value : ""); const handleFocusDate = () => { setDateFocused(true); }; const dateHandler = (e) => { setDate(e.target.value); const choosenDate = new Date(e?.target?.value ? e?.target?.value : date); const inputDate = new Date(choosenDate); let year = inputDate.getFullYear(); let month = String(inputDate.getMonth() + 1).padStart(2, "0"); let day = String(inputDate.getDate()).padStart(2, "0"); let hours = String(inputDate.getHours()).padStart(2, "0"); let minutes = String(inputDate.getMinutes()).padStart(2, "0"); let seconds = String(inputDate.getSeconds()).padStart(2, "0"); let milliseconds = String(inputDate.getMilliseconds()).padStart(3, "0"); let outputDateString = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}.${milliseconds}`; onChange(outputDateString); }; const combinedStyle = { width: width ? width : "350px", height: height ? height : "40px", backgroundColor: disabled ? "#f5f5f5" : "", ...style, }; useEffect(() => { const handleClickOutside = (event) => { if (dateRef.current && !dateRef?.current?.contains(event.target)) { setDateFocused(false); } }; document.addEventListener("mousedown", handleClickOutside); return () => { document.removeEventListener("mousedown", handleClickOutside); }; }, []); useEffect(() => { setDate(value); }, [value]); return ( <div> <div> <p className={classes.label}> {label ? label : ""} {required && <span className={`required`}>*</span>} </p> </div> <div className={classes.parentContainer}> <div ref={dateRef} style={{ width: width ? width : combinedStyle?.width ? combinedStyle?.width : "350px", }}> <div style={combinedStyle} onFocus={handleFocusDate} className={`${className?className:classes.inputFieldContainer} ${ dateFocused && classes.focused }`}> <input disabled={disabled} style={{ backgroundColor: disabled ? "#f5f5f5" : "" }} className={classes.inputField} placeholder={placeHolder ? placeHolder : "Date picker"} onFocus={(e) => (e.target.style.border = "none")} onBlur={(e) => (e.target.style.borderBottom = "none")} type="date" onChange={dateHandler} value={date} {...props} /> </div> </div> </div> </div> ); }; export default DatePicker;