Skip to content

React forms with Arabic and RTL

Build Arabic React forms with field-specific direction, stable controlled inputs, translated validation and form library integrations.

By , Founder of Ritla

Guide12 min read

A React field can have an Arabic label, accept Arabic typing, and still put its caret and punctuation in the wrong place. The cause may be a shared input that discards dir, a controlled value rewritten on every keystroke, or an LTR setting applied to the entire field, including its error message.

These are separate failures. Changing the form library will not repair the field's direction contract. Translating the validation schema will not preserve a draft that a locale switch remounts.

Consider a microscope service request. Its laboratory location is expected in Arabic, its fault description may contain either language, and its manufacturer serial number has a fixed Latin format. All three belong in an Arabic interface. They should not all receive the same input direction.

Choose direction for the value, not the form library#

Set the Arabic document's semantic direction with dir="rtl" and its language with lang="ar". Within that interface, decide what each control accepts. Language identifies the language of text; direction establishes its base reading direction. Neither translates a label. W3C's direction guidance explains the HTML boundary.

For the service request, write the contract before implementing the component:

FieldContent contractDirection
Laboratory locationArabic location descriptionrtl
Fault descriptionArabic or English free textauto, with the empty state reviewed
Manufacturer serialFixed Latin identifier, such as 8426-LENSltr
Contact email or equipment documentation URLMachine-format addressExplicit ltr
Service categoryTranslated Arabic option labelsInherit RTL or set rtl

Use dir="auto" when the content's direction is unknown. It follows the first strong directional character, rather than the user's interface locale. An English model name at the beginning of an otherwise Arabic fault report can therefore select LTR. Automatic detection is a policy choice, not a guarantee about the writer's intended paragraph direction.

In Chromium 151, checked on September 24, 2026, an empty auto-directed input resolved LTR even with an Arabic placeholder. If the location field must open at the Arabic reading edge, give it dir="rtl". For the bilingual fault description, decide whether the auto-directed empty state is acceptable. Do not introduce a React direction detector merely to hide that decision. See how dir="auto" works for its limits.

Follow the prop to the native control#

Inspect the rendered input, not just the JSX calling your design system. A parent can pass dir="ltr" correctly while the wrapper silently drops it.

Problem: this location field accepts dir at its call site but never applies it. Its hard-coded input direction also prevents inheritance from helping.

jsx
export function ServiceInput({ label, id, name, defaultValue }) {  return (    <div className="service-field">      <label htmlFor={id}>{label}</label>      <input id={id} name={name} defaultValue={defaultValue} dir="ltr" />    </div>  );}

Better: the same field forwards input attributes, event handlers and its DOM ref. Save this version as ServiceInput.jsx for the later examples.

jsx
import { forwardRef, useId } from "react"; export const ServiceInput = forwardRef(function ServiceInput(  { label, help, error, id, dir, "aria-describedby": describedBy, ...props },  ref) {  const generatedId = useId();  const inputId = id ?? generatedId;  const helpId = help ? `${inputId}-help` : undefined;  const errorId = error ? `${inputId}-error` : undefined;  const description = [describedBy, helpId, errorId].filter(Boolean).join(" ");   return (    <div className="service-field">      <label htmlFor={inputId}>{label}</label>      <input        {...props}        ref={ref}        id={inputId}        dir={dir}        aria-invalid={error ? true : undefined}        aria-describedby={description || undefined}      />      {help && <p id={helpId}>{help}</p>}      {error && <p id={errorId} className="service-error">{error}</p>}    </div>  );});

Callers choose the control's direction; the wrapper owns its label and error association. Additional descriptions are retained instead of overwritten. The Arabic label and error remain outside the input's LTR boundary when the same component renders a serial number.

forwardRef supports a component shared with React 18 applications. In React 19, a function component can receive ref as a prop instead. Whichever API your supported version uses, attach that ref to the actual input. React documents the version distinction.

useId avoids collisions when several requests appear on one page. It requires matching server and client component trees for server rendering. Do not replace it with a translated label or a random value generated during rendering. React's useId reference covers those constraints.

For the Arabic location, add this usage beneath the corrected component in the same file:

jsx
export function LaboratoryLocation() {  return (    <ServiceInput      name="laboratoryLocation"      label="موقع المختبر"      defaultValue="مختبر الطحالب"      dir="rtl"    />  );}

In DevTools, select that native input and check both its dir attribute and computed direction. If the attribute is present but a stylesheet forces another direction, prop forwarding is no longer the failing layer. Inspect the winning declaration. Adding more props to the wrapper will not beat an unrelated CSS rule.

Keep editing state in the order the user entered#

Arabic text does not require a reversed React string. The browser displays bidirectional runs from the logical value. Reversing an array of characters corrupts the stored text and can separate combining marks from their letters.

This bilingual fault note keeps the value untouched. It is a separate component, with its own visible label:

jsx
import { useId, useState } from "react"; export function FaultNote() {  const id = useId();  const [note, setNote] = useState("");   return (    <div className="service-field">      <label htmlFor={id}>وصف العطل</label>      <textarea        id={id}        name="faultNote"        dir="auto"        dirname="faultNoteDirection"        rows={5}        value={note}        onChange={(event) => setNote(event.currentTarget.value)}      />    </div>  );}

For a controlled textarea, value is the editing value and onChange updates it. Do not put the initial text between textarea tags in React. React's textarea reference describes its controlled and uncontrolled APIs.

For a controlled input, update state synchronously to the DOM value. Debouncing that update or rewriting the value can cause caret problems; debounce a lookup or validation request instead. Initialize a controlled text value with an empty string, rather than changing from undefined to a string after data arrives. React's input troubleshooting covers both failures.

To debug a reported caret jump, compare the value before and after the change handler, then check whether the input DOM node survived the render. A new node points toward component identity or keys. An unchanged node with a rewritten value points toward formatting. Neither observation is evidence that Arabic strings need manual reversal.

Submit direction metadata only when it has a purpose#

The fault note includes dirname="faultNoteDirection". When the browser constructs form data, this names an additional entry containing the textarea's resolved direction, ltr or rtl. It does not reverse the text or identify its language. MDN's dirname reference describes the submission behavior.

That metadata can matter if a service agent later reads the report in an English dashboard, particularly when the product allows the writer to override automatic direction. Persist the chosen direction alongside the note if maintaining that choice is part of the record's contract. Accept only the supported direction values on the receiving side.

A JSON object assembled from React state, Formik values or registered React Hook Form fields is a different submission path. Do not assume it includes an extra browser-generated entry. Inspect the actual payload and explicitly include direction metadata if your API requires it. The one-field serial example below has no such requirement.

If the reader view always applies automatic direction again and authors cannot override it, storing a second value may add no useful information. Keep the distinction explicit: a field's text, its direction and its language are separate pieces of data, and only some products need to retain all three.

Separate draft text from submission normalization#

The serial field is an identifier, so keep it as a string. Parsing it as a number would discard letters and potentially meaningful leading zeroes. type="number" is not an identifier control.

This example's manufacturer contract accepts four Western digits, a hyphen and four uppercase Latin letters. That is a rule for this fictional service system, not a rule for Arabic interfaces generally. Tell users the accepted format before rejecting it.

If your product accepts Arabic-Indic digits too, define an explicit conversion at the validation or submission boundary and use the same policy on the server. Check pasted values as well as keyboard entry. Do not silently remove every character outside ASCII from free-text descriptions; that would delete the report itself.

Avoid applying capitalization, trimming or digit conversion to the controlled editing value on every change. If normalization changes what will be submitted, make the resulting value reviewable at a deliberate boundary. For an identifier printed on hardware, preserving the entered form and explaining a mismatch may be preferable to guessing a correction.

inputMode only suggests an on-screen keyboard. It does not establish direction or validate the value. A numeric keyboard would also be a poor choice for this serial because users need Latin letters and a hyphen. MDN's inputmode reference distinguishes the keyboard hint from constraints.

Input methods can have a composition phase. If a mask, shortcut or live validator changes text during composition, test it with the keyboards your users use. Preserve draft updates while postponing destructive transformations or premature actions. Arabic typing does not universally involve composition, but a bilingual form must not assume every input event is a finished character. MDN describes composition sessions.

Store validation meaning separately from translated copy#

A schema created with English error strings can leave those strings in form state after the interface switches to Arabic. Rebuilding the schema does not, by itself, replace an error already stored by the form library.

Return a stable issue code and translate it when rendering. The error's meaning survives a locale change; its wording follows the current interface. Save these shared definitions as serviceValidation.js:

js
export function serialIssue(value) {  if (!value.trim()) return "serial_required";  if (!/^[0-9]{4}-[A-Z]{4}$/.test(value)) return "serial_format";  return null;} export const serviceCopy = {  en: {    serialLabel: "Manufacturer serial number",    serialHint: "Enter the serial exactly as printed on the instrument.",    serial_required: "Enter the instrument's serial number.",    serial_format: "Use four digits, a hyphen and four uppercase Latin letters.",    generic: "Check this value and try again.",    submit: "Continue with service request"  },  ar: {    serialLabel: "الرقم التسلسلي للجهاز",    serialHint: "أدخل الرقم كما يظهر على الجهاز.",    serial_required: "أدخل الرقم التسلسلي للجهاز.",    serial_format: "استخدم أربعة أرقام، ثم شرطة، ثم أربعة أحرف لاتينية كبيرة.",    generic: "تحقق من هذه القيمة وحاول مجدداً.",    submit: "متابعة طلب الصيانة"  }};

This validator treats whitespace-only input as missing, while other surrounding whitespace fails the documented exact format. There is no hidden trim on submission. Decide explicitly if your production contract should accept that whitespace instead.

The same separation helps server responses. Map known server codes to complete localized sentences and provide a translated fallback for an unknown code. Do not print a database field name or an English exception in the error slot. If a server returns translated messages, its response locale becomes part of the request contract and locale-switch handling.

Some schema integrations expect message strings. A stable code can occupy that string slot, as below, provided every display path translates it. Otherwise revalidate existing errors after changing the message catalog, and preserve the user's values and touched state. Merely changing a provider does not translate arbitrary strings held elsewhere.

React Hook Form needs the native field contract#

For a native input, React Hook Form's register supplies a name, handlers and ref. Those must reach the control. A custom wrapper that drops the ref can also break focusing an invalid field. The registration documentation explains the connection.

This one-field form uses the preceding files. Its locale prop is a validated ar or en value; its onContinue prop receives valid form data.

jsx
import { useForm } from "react-hook-form";import { ServiceInput } from "./ServiceInput.jsx";import { serialIssue, serviceCopy } from "./serviceValidation.js"; export function SerialStep({ locale, onContinue }) {  const copy = serviceCopy[locale];  const { register, handleSubmit, formState: { errors } } = useForm({    defaultValues: { serial: "" }  });  const issue = errors.serial?.message;  const message = issue    ? (Object.hasOwn(copy, issue) ? copy[issue] : copy.generic)    : undefined;   return (    <form dir={locale === "ar" ? "rtl" : "ltr"} lang={locale} noValidate      onSubmit={handleSubmit(onContinue)}>      <ServiceInput        {...register("serial", { validate: (value) => serialIssue(value) ?? true })}        label={copy.serialLabel}        help={copy.serialHint}        error={message}        dir="ltr"        autoCapitalize="none"        spellCheck={false}      />      <button type="submit">{copy.submit}</button>    </form>  );}

Changing locale rerenders the stored issue code through the new catalog. The serial retains its LTR direction in either interface. This local form boundary also makes the example usable in a component fixture; a full Arabic page still needs document direction.

For a controlled third-party widget, use the library's Controller integration. Forward its field value, handlers and ref through the widget's documented native-input API. Do not also spread register for that field: the Controller documentation warns against double registration. Direction is still a widget or DOM setting, not a validation option.

An adapter test should therefore cover submission and error focus as well as attributes. A field can look correct while failing to register its value, and a successfully registered value can still render with the wrong direction.

Formik and schema libraries follow the same boundary#

Formik's useField returns field bindings and metadata, including touched state and the stored error. Pass the bindings to the same native wrapper. Translate its issue code when deciding what error to show. Formik's useField API documents that separation.

For this service form, a Formik validator can call serialIssue(values.serial) and return { serial: issue } when an issue exists, or {} otherwise. The field renderer reads meta.touched and meta.error before looking up the current message. This uses the same manufacturer contract as the React Hook Form example rather than maintaining two divergent regexes. Formik's validation API accepts a synchronous errors object or a promise resolving to one.

When Yup, Zod or another resolver constructs errors, inspect its output rather than assuming its default messages are translated. Review messages produced by required rules, type coercion, nested array paths and server failures. A translated label does not cover those paths.

Do not tie initial values to translated labels. Keep field names and option values stable across languages; translate their visible text. For a service-category select, changing the label should not change the selected category identifier. React controls a select through its own value, rather than selected on individual options. React's select reference documents that API. Inspect custom select menus separately, especially if they render outside the form through a portal.

Keep errors in the interface's direction#

Setting dir="ltr" on a serial field's outer wrapper also changes the base direction of its Arabic label, hint and error. Narrow the boundary to the input, as ServiceInput does. The same applies to email, URL and telephone controls: their values need LTR while their explanation remains part of the Arabic interface.

Do not put a formatter's invisible direction marks into the editable value to compensate for an incorrect boundary. A serial that looks acceptable while editing can still become ambiguous when echoed in a confirmation sentence. Render that read-only token in its own isolation boundary. The distinction is covered in bidi isolation.

Allow error copy to grow. This CSS applies to the shared field and fault note:

css
.service-field {  display: flex;  flex-direction: column;  gap: 0.625rem;  min-inline-size: 0;} .service-field :is(input, textarea) {  box-sizing: border-box;  inline-size: 100%;  min-inline-size: 0;  padding-block: 0.75rem;  padding-inline: 0.875rem;  font: inherit;  text-align: start;} .service-field p {  margin: 0;  line-height: 1.6;  overflow-wrap: anywhere;}

text-align: start follows each control's own direction. It does not change that direction. MDN's alignment reference explains the distinction. The symmetric padding preserves the English layout, while the flexible height lets an Arabic error wrap instead of occupying an absolutely positioned line below the input.

Associate errors programmatically and explain the correction in text. Do not announce every incomplete keystroke as an alert. On failed submission, provide a deliberate route to the affected fields, with a summary or focus handling appropriate to the form. W3C's form notification guidance covers inline feedback and submission feedback. The wrapper supplies associations; it does not implement the entire notification policy.

Choose who owns validation messages#

Browser validation bubbles and application errors are different channels. In Chromium 151 with an English browser interface, an Arabic page still produced English built-in validation copy. Changing lang alone did not translate it.

The example uses noValidate because its application validator owns submission errors. That choice requires the application to supply useful feedback. It does not make invalid data acceptable to the server. MDN's constraint validation guide explains how native constraints and interactive validation relate.

If you keep native validation and call setCustomValidity, update the custom message for the current language and clear it with an empty string when the problem is resolved. A nonempty custom message keeps the control invalid. Replacing only the adjacent React error leaves native validity untouched. MDN documents setCustomValidity.

Keep server validation authoritative for the manufacturer format and service permissions. An Arabic client message should describe a failure the server actually recognizes, rather than promising that every visually plausible identifier will be accepted.

Preserve the request while language and data change#

A locale switch should change labels and presentation without becoming an accidental reset operation. Do not use key={locale} on the form merely to force new translations. Changing a key resets component identity and its state, as React's state preservation guide explains. Use a record identifier when switching to a different service request intentionally requires a reset.

Also inspect effects that call a library's reset method after every locale change. They can overwrite the draft even when the component stays mounted. React Hook Form distinguishes initial defaults, reactive values and reset options in its useForm documentation. Define whether incoming record data may replace dirty fields instead of making translation changes trigger that policy.

For server rendering, resolve the initial locale and initial request data before producing the markup, then hydrate with matching inputs. A field that is RTL on the server and LTR on the client's first render has an initialization defect. A post-mount effect can conceal the mismatch after the user has already seen it.

Async serial lookups need another identity check. A response for an earlier serial must not attach an error to the replacement value. Associate the response with the requested value or request generation and discard stale results. If messages are localized on the server, account for the requested locale too. Translate stable error codes at render time where possible.

Reproduce the editing failure before accepting the fix#

Use an actual browser for caret, selection and visual order. A DOM assertion that value equals the submitted string cannot prove that punctuation appeared at the expected edge.

Start with the location field empty, then type an Arabic location and confirm its RTL direction at the native input. For the auto-directed note, enter تنقطع الإضاءة عند تدوير القرص, replace it with an English report, and delete everything again. Inspect the empty state as well as the populated states. Repeat with a Latin model name preceding Arabic text.

In the serial field, enter 8426-LENS, move into the digit group, replace a selection, paste the complete value and undo the edit. Confirm that the submitted string retains its source order. Review the visible identifier separately. Then submit an empty or malformed serial and verify that focus reaches the native field through the wrapper's ref.

Leave an error visible and switch languages without submitting again. Its wording should change while the serial, dirty state and correction remain available. Test a slow lookup while editing the serial, and resolve the earlier request last. It must not overwrite the newer result. At a narrow viewport and enlarged text size, check that the wrapped error does not collide with the next field or submit action.

A free Ritla scan can report text inputs rendered LTR where Arabic input is expected R023, tel/email/url inputs rendered RTL R070, and untranslated form labels / validation / help text R071. For the next debugging step, use dynamic text direction when a field's content changes language, or Arabic localization testing when the form's error paths still expose English copy.

Checks in this guide

See what your Arabic pages are hiding

Paste a URL. Ritla renders the page on desktop and mobile, runs every check, and shows the top issues with screenshot evidence.

Scan a page freeBrowse the checks