Skip to content

Instantly share code, notes, and snippets.

@alieslamifard
Last active April 26, 2021 12:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alieslamifard/364862613408a98139da3cab40abbeb9 to your computer and use it in GitHub Desktop.
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)
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