Last active
June 29, 2022 11:43
-
-
Save anlisha-maharjan/4371c5604a0795e7f62bd87d2dd3ba63 to your computer and use it in GitHub Desktop.
A custom react time-picker component combining react-datetime & react-input-mask packages.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useState } from "react"; | |
import Datetime from "react-datetime"; | |
import InputMask from "react-input-mask"; | |
import moment from "moment"; | |
const CustomTimePicker = ({ label, classes, ...props }) => { | |
const [selectedTime, setSelectedTime] = useState("00:00"); | |
const [formatChars] = useState({ | |
1: "[0-2]", | |
2: "[0-9]", | |
3: "[0-5]", | |
4: "[0-9]", | |
5: "[0-5]", | |
6: "[0-9]", | |
}); | |
const handleTimeChange = (dateString) => { | |
if (dateString) { | |
setSelectedTime(moment(dateString, "HH:mm")); | |
} else { | |
setSelectedTime(null); | |
} | |
}; | |
const beforeMaskedValueChange = (newState) => { | |
const { value } = newState; | |
// Conditional mask for the 2nd digit base on the first digit | |
if (value.startsWith("2")) formatChars["2"] = "[0-3]"; | |
// To block 24, 25, etc. | |
else formatChars["2"] = "[0-9]"; // To allow 05, 12, etc. | |
return { value, selection: newState.selection }; | |
}; | |
const maskInput = (props) => { | |
return ( | |
<> | |
<InputMask | |
className="field" | |
mask="12:34" | |
maskchar="0" | |
formatChars={formatChars} | |
beforeMaskedValueChange={beforeMaskedValueChange} | |
{...props} | |
/> | |
</> | |
); | |
}; | |
return ( | |
<div className={`field-group mb-0`}> | |
<label htmlFor="" className={`field-label`}> | |
{label} | |
</label> | |
<div className={`field-wrap icon-end kc-timepicker outlined`}> | |
<Datetime | |
value={selectedTime} | |
open={true} | |
dateFormat={false} | |
timeFormat={"HH:mm"} | |
renderInput={maskInput} | |
inputProps={{ | |
className: `field ${classes?.input || ""}`, | |
}} | |
onChange={handleTimeChange} | |
/> | |
</div> | |
</div> | |
); | |
}; | |
export default CustomTimePicker; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment