Skip to content

Instantly share code, notes, and snippets.

@Mood-al
Last active March 15, 2023 22:49
Show Gist options
  • Save Mood-al/af31075f6feb1ab3cbcdafa6a5936d62 to your computer and use it in GitHub Desktop.
Save Mood-al/af31075f6feb1ab3cbcdafa6a5936d62 to your computer and use it in GitHub Desktop.
a react custom hook that detects the direction of an input based on its value
import { useEffect, useState } from "react";
import { isRTL } from "../utils/isRTL";
const useInputDirectionDetector = (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 useInputDirectionDetector;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment