Last active
April 26, 2021 12:19
-
-
Save alieslamifard/364862613408a98139da3cab40abbeb9 to your computer and use it in GitHub Desktop.
React input component with Persian/Arabic to English number/digit compatibility (Tested with react-hook-form)
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, { InputHTMLAttributes, useEffect, useRef } from 'react'; | |
// Persian/Arabic To English Number | |
const f2e = (event) => { | |
event.target.value = event.target.value | |
.replace(/[٠-٩]/g, (d) => '٠١٢٣٤٥٦٧٨٩'.indexOf(d)) | |
.replace(/[۰-۹]/g, (d) => '۰۱۲۳۴۵۶۷۸۹'.indexOf(d)); | |
return event; | |
}; | |
const useForwardedRef = (ref) => { | |
const innerRef = useRef(null); | |
useEffect(() => { | |
if (!ref) return; | |
if (typeof ref === 'function') { | |
ref(innerRef.current); | |
} else { | |
ref.current = innerRef.current; | |
} | |
}, [ref]); | |
return innerRef; | |
}; | |
const Input = React.forwardRef<HTMLInputElement, InputHTMLAttributes<HTMLInputElement>>( | |
(props, ref) => { | |
const innerRef = useForwardedRef(ref); | |
useEffect(() => { | |
innerRef.current?.addEventListener('keyup', f2e); | |
return () => { | |
innerRef.current?.removeEventListener('keyup', f2e); | |
}; | |
}, [innerRef]); | |
return <input {...props} ref={innerRef} />; | |
}, | |
); | |
export default Input; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment