Created
October 2, 2022 20:12
-
-
Save Mood-al/5e0e2cdc23641caf37fed381d6bfb611 to your computer and use it in GitHub Desktop.
useInputValueLangaugeDetector.js
This file contains hidden or 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 { useEffect, useState } from "react"; | |
import { isRTL } from "../utils/isRTL"; | |
const useInputValueLangaugeDetector = (value, locale) => { | |
const [dir, setDir] = useState(); | |
const [focussed, setFocussed] = useState(false); | |
/* If the user is typing and the language is Arabic, then set the direction to | |
right-to-left. */ | |
useEffect(() => { | |
if (value === "" && locale === "ar") { | |
setDir("rtl"); | |
return; | |
} | |
/* The above code is setting the direction of the text to right to left if the user is focussed on | |
the text box. */ | |
if (focussed) { | |
isRTL(value) ? setDir("rtl") : setDir("ltr"); | |
} | |
}, [value, focussed, locale]); | |
/* Using useEffect to update the direction of the page based on the locale. */ | |
useEffect(() => { | |
locale === "ar" ? setDir("rtl") : setDir("ltr"); | |
}, [locale]); | |
/** | |
* When the input field is focused, set the direction to rtl if the input field is empty and the | |
* language is arabic, otherwise set the direction to ltr | |
* @param e - The event object. | |
* @returns The `onInputFocus` function is being returned. | |
*/ | |
const onInputFocus = (e) => { | |
setFocussed(true); | |
if (e.target.value === "" && locale === "ar") { | |
setDir("rtl"); | |
return; | |
} | |
isRTL(e.target.value) ? setDir("rtl") : setDir("ltr"); | |
}; | |
/** | |
* When the input field loses focus / blurred, set the direction to the direction of the language | |
* @param e - The event object that was passed to the onInputBlur function. | |
*/ | |
const onInputBlur = (e) => { | |
setFocussed(false); | |
if (e.target.value === "" && locale === "ar") { | |
setDir("rtl"); | |
return; | |
} | |
locale === "ar" ? setDir("rtl") : setDir("ltr"); | |
}; | |
return { | |
dir, | |
onInputBlur, | |
onInputFocus | |
}; | |
}; | |
export default useInputValueLangaugeDetector; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment