useTextDirection

change dir of the element’s text

useTextDirection reads and updates the dir attribute on a target element (default: <html>), controlling the text direction. It returns a tuple of the current direction value ("ltr", "rtl", or "auto") and a setter function. This is essential for building internationalized applications that support right-to-left languages like Arabic, Hebrew, and Persian.

When to Use

  • Supporting bidirectional (BiDi) content in multilingual applications
  • Building language switchers that toggle between LTR and RTL layouts
  • Dynamically adjusting text direction based on user input or content language

Notes

  • SSR-safe: Returns the initialValue (default: "ltr") and a no-op setter during server-side rendering. No document access occurs on the server.
  • Target selector: By default, the hook sets dir on the <html> element. Use the selector option to target a specific element for scoped direction changes.
  • Related hooks: See also usePreferredLanguages for detecting the user’s language preferences, which can inform the text direction choice.

Usage

Live Editor
function Demo() {
  const [dir, setDir] = useTextDirection({
    selector: "#_useTextDirectionDemo",
  });

  const text = useMemo(
    () =>
      dir === "ltr"
        ? "This paragraph is in English and correctly goes left to right."
        : "This paragraph is in English but incorrectly goes right to left.",
    [dir],
  );

  const handleOnClick = () => {
    const value = dir === "rtl" ? "ltr" : "rtl";
    setDir(value);
  };

  return (
    <div id="_useTextDirectionDemo">
      <p>{text}</p>
      <button onClick={handleOnClick}>
        <span>{dir.toUpperCase()}</span>
      </button>
      <span>Click to change the direction</span>
    </div>
  );
};

render(<Demo/>);
Result

API

useTextDirection

Returns

readonly [UseTextDirectionValue, (value: UseTextDirectionValue) => void]: A tuple with the following elements:

  • The current value of the text direction.
  • A function to update the value of the text direction.

Arguments

ArgumentDescriptionTypeDefaultValue
optionsoptional paramsUseTextDirectionOptions | undefined-

UseTextDirectionOptions

PropertyDescriptionTypeDefaultValue
selectorCSS Selector for the target element applying tostring'html'
initialValueInitial valueUseTextDirectionValue'ltr'

UseTextDirectionValue

Type

export type UseTextDirectionValue = 'ltr' | 'rtl' | 'auto'