React RTL: the complete guide
Learn how to set direction in React, avoid hydration and portal bugs, configure component libraries, and render Arabic content safely.
By Omran Khleifat, Founder of Ritla
Guide13 min read
A React page can render Arabic text while its document remains LTR, its menu opens with English geometry, and a portal-mounted preview inherits direction from somewhere else. Passing a locale through the component tree does not establish the browser's direction or configure every component library.
React supports native dir and lang props, but it does not choose your application's reading direction, translate its strings, or mirror arbitrary artwork. Those decisions belong to the application and the libraries it uses. The browser then applies HTML direction and CSS layout rules to the resulting DOM.
This guide uses a fictional tea-tasting notebook to connect those layers: its initial document, reusable panels, a portal preview, and mixed-direction sample references. The same approach applies when adding Arabic to an existing React product.
Separate the responsibilities before adding a provider#
Locale, direction, and translation overlap, but they are not interchangeable configuration values.
| Layer | What it controls | What it does not establish by itself |
|---|---|---|
| Locale selection | Which supported interface configuration to load | The document's HTML attributes |
lang | The declared language of content | RTL layout |
dir | Semantic text direction and direction-sensitive layout | Translated messages or reflected SVGs |
| React context | Values available to descendant React components | Browser inheritance across a portal boundary |
| Library direction setting | The library's directional behavior | All application CSS and content direction |
| RTL style processing | Rewriting supported physical styles | Correct data order or correct navigation meaning |
Treat one resolved locale configuration as the input to these layers. Avoid separate booleans whose values can disagree, such as an Arabic translation bundle paired with an English theme direction.
Scope the configuration to the interface you support. An Arabic application can contain English content without becoming an English interface. Conversely, an Arabic quotation inside an English interface does not require changing the document root.
Check the rendered attributes at each boundary instead of treating a provider's presence as proof of support. React's common DOM props reference documents the native component props that wrappers need to preserve.
Resolve the locale before rendering the document#
For a server-rendered application, produce the correct attributes in the initial HTML. Do not ship an English shell and rely on an effect to turn it into an Arabic document after hydration.
Here is a small supported-locale registry. It intentionally supports only the application's two interface choices; normalize and validate route or account settings before selecting one.
export const notebookLocales = { ar: { lang: 'ar', dir: 'rtl', title: 'دفتر تذوّق الشاي', preview: 'معاينة ملاحظة التذوّق' }, en: { lang: 'en', dir: 'ltr', title: 'Tea tasting notebook', preview: 'Tasting note preview' }}; export function notebookUi(locale) { if (!Object.hasOwn(notebookLocales, locale)) { throw new Error('Unsupported notebook locale'); } return notebookLocales[locale];}Use the resolved configuration in the framework's root document or layout. This document component assumes notebookUi is in scope from the registry above:
export function NotebookDocument({ locale, children }) { const ui = notebookUi(locale); return ( <html lang={ui.lang} dir={ui.dir}> <head> <meta charSet="utf-8" /> <title>{ui.title}</title> </head> <body>{children}</body> </html> );}This is the document shell, not a component to mount inside an existing body's React root. Integrate it through the framework's document mechanism or server-rendering entry point. React's server-rendering documentation demonstrates rendering a complete HTML document.
For a client-only application, arrange the initial HTML or bootstrap step to establish the resolved document attributes before displaying the localized UI. If account preferences arrive later, choose an explicit loading or redirect strategy. Showing a fully interactive interface with contradictory direction is not a useful intermediate state.
Make the first client render agree with the server#
An Arabic route rendered on the server and an English locale read from browser storage can produce different first renders. The mismatch can affect labels, attributes, generated styles, and element order.
Pass the resolved server locale into the initial client state through the framework's supported data mechanism. Apply the same message resources and rendering decisions on both sides. If a stored preference conflicts with the route, resolve that conflict deliberately after the initial render or redirect before rendering the page.
hydrateRoot expects the initial client output to match the server HTML. React does not guarantee that mismatched attributes will be repaired. Adding suppressHydrationWarning to the document is not a direction setup strategy; it conceals evidence without reconciling the inputs.
An effect is also too late to determine the server's HTML. React's useEffect documentation states that effects run on the client, and visual work can occur after the browser paints. Use effects to synchronize with an external owner when necessary, rather than making them the source of the initial locale.
Check a cold load as well as an in-app language switch. Disable or delay application JavaScript and inspect the initial document attributes and visible shell. Then enable hydration and inspect warnings. A client-navigation screenshot can miss an initial LTR shell completely.
Formatting is part of that agreement. If the server and client choose different digit conventions or timezones, their text can differ even when both have lang="ar". Specify the formatting inputs that matter to the product.
Localize the shell and fallback branches too#
A translated workspace can still stream an English loading message or display an English error fallback when a child fails. Resolve the shell's language independently of whether the notebook data or a large editor bundle has finished loading; React's Suspense documentation describes where loading fallbacks render.
Keep the resolved UI configuration available above the boundary whose fallback needs it. If a provider exists only inside the suspended content, a fallback outside that subtree cannot read its value. Check the actual tree placement rather than adding an RTL class to the eventual editor and assuming its fallback shares the setup.
The same review applies to errors, empty collections, and permission failures. Each branch should receive the interface configuration and expose translated actions. A retry button produced by an error boundary can be a different component from the normal workspace toolbar, with different prop forwarding and styles.
Trigger these paths deliberately. Delay the notebook data, delay a dynamically loaded component, and simulate a handled failure. Inspect the initial shell and each replacement, including their portal-mounted messages. Confirm that the same locale remains in force when a retry succeeds. Testing only a warm route with cached translations and data misses these intermediate outputs.
Forward direction through reusable component boundaries#
A native element receives dir when React renders that prop. A custom component receives a JavaScript prop and must decide where to put it.
Problem: this wrapper drops the caller's direction and language:
export function TastingPanel({ children }) { return <section className="tasting-panel">{children}</section>;}Calling it with dir="rtl" does not add that attribute to the section. The wrapper has ignored the prop. Inspecting the React component's props can therefore give a different impression from inspecting the rendered DOM.
Better: forward the supported attributes to the same semantic boundary:
export function TastingPanel({ dir, lang, children }) { return ( <section className="tasting-panel" dir={dir} lang={lang}> {children} </section> );}Use this wrapper as <TastingPanel dir="rtl" lang="ar"> around the relevant content. With neither prop supplied, HTML inheritance still applies. The wrapper does not need to repeat the document's attributes on every panel.
Review design-system wrappers that replace their host element, render several roots, or forward only a restricted prop list. Establish which rendered node owns direction, accessible labels, and layout styles. A prop forwarded to an invisible wrapper may still leave the interactive surface outside its intended boundary.
This is also why a general “RTL enabled” React provider cannot repair every custom component. The DOM node must receive the semantics, or inherit them from its actual ancestor.
Keep styles logical instead of branching every component#
For the notebook's panel accent, the design calls for a border and padding at inline start. A physical implementation fixes them to the left:
Problem
.tasting-panel { border-left: 4px solid currentColor; padding-left: 1.25rem;}Better
.tasting-panel { border-inline-start: 4px solid currentColor; padding-inline-start: 1.25rem;}The LTR layout keeps its left border and spacing; RTL places them at the right. This changes the same panel's directional relationship without introducing two copies of its stylesheet. See CSS logical properties for RTL for the property mappings.
React inline styles use camel-cased names, so the equivalents are borderInlineStart and paddingInlineStart. CSS Modules do not change a declaration's meaning: a locally scoped padding-left remains physical. The same review applies to styles created by a styling library.
Keep source order meaningful. A normal flex row responds to direction; reversing an array or adding row-reverse as a blanket Arabic fix can reverse a layout that already follows RTL. Tabs, action groups, and tasting entries should retain their logical relationships. RTL flexbox explains that distinction.
Some properties remain physical by design. A graph's coordinates, a physical drag direction, or a transform cannot be converted by renaming every occurrence of “left.” Audit the relationship the property expresses. Handle navigation glyphs and animation offsets explicitly rather than expecting React or logical padding to redraw them.
Keep record identity separate from visual direction#
RTL layout does not require reversing the tasting records. The collection might be ordered by creation time, tasting session, or an explicit user sort. Preserve that ordering unless the product actually changes it, then let layout determine how the sequence occupies the page.
Use stable record identifiers as React list keys. If a component stores an expanded state or local draft and the list uses array indexes as keys, reordering can associate that state with a different record. A direction patch that reverses the array can therefore introduce a content bug as well as a visual one. React's list-rendering guidance explains why keys identify items across changes.
Do not mutate a shared records array with reverse() during render. Keep presentation derivation separate from the original data, and make any intended sort explicit. Even a nonmutating reversal still changes the sequence; copying the array does not make that a direction requirement.
Test by opening one tasting entry, entering a draft, then changing the interface language and the sort order separately. Check the record identity associated with the draft each time. This verifies that the component state follows the intended sample rather than whichever row occupies the same screen position.
React context does not replace HTML inheritance#
Context is useful for sharing the notebook's resolved UI configuration with components. It can supply direction to an icon adapter, formatter, or third-party provider. It does not modify an HTML attribute simply because the context value contains dir: 'rtl'.
React's useContext reference describes subscribing to a provider's value. Consumers still need to apply that value to the relevant output or library API. Decide where that happens instead of repeating document mutations in many components.
Keep document ownership explicit. A full-page application can own the root attributes; an embedded tasting widget should usually own a local boundary. An effect in the embedded widget that rewrites document.documentElement.dir changes its host page as well, which exceeds that widget's intended scope.
Separate roots need attention too. A second React root is not automatically a descendant of the first root's context provider. Give each root the configuration it requires while maintaining a consistent document-level direction contract.
Configure portals at their actual DOM location#
A preview rendered with createPortal remains in the React tree for context and event propagation. Its DOM nodes are inserted at the portal target, so browser inheritance follows that target's ancestors. Those two trees answer different questions.
The React portal reference documents this separation. A component can read Arabic UI context inside a portal while its DOM inherits LTR direction from the host document.
This read-only preview boundary receives the resolved ui object and a stable mounted DOM target from its caller:
import { createPortal } from 'react-dom'; export function TastingPreview({ host, ui, children }) { if (!host) return null; return createPortal( <aside lang={ui.lang} dir={ui.dir} aria-label={ui.preview}> {children} </aside>, host );}The caller obtains host only in the browser. In an SSR integration, keep it absent on the server and on the matching first client render, then supply it after mounting or when opening the preview. Do not read document during server rendering to locate the target.
The example establishes direction and language; it does not implement a modal's focus management or dismissal behavior. Use the appropriate accessible component when the preview is modal.
If the entire document is already RTL, the portal may inherit that correctly. Explicit local attributes matter when the widget is embedded, the host has another direction, or multiple interface surfaces coexist. Inspect menus, tooltips, and notifications as well as the obvious preview panel.
Configure the component library's own direction layer#
Library direction can control keyboard movement, placement defaults, animations, or generated styles. Setting dir on the document does not establish that every library has consumed it.
For Material UI, follow the installed version's RTL setup. Its documented setup distinguishes HTML direction, theme direction, and RTL style processing. For the Emotion styling path, configure the documented RTL plugin pipeline and preserve the required style processing around it. A theme option alone is not a substitute for the other layers.
When switching between LTR and RTL, select the matching theme and style configuration together. Review cache identity and the framework's SSR style integration, rather than mutating a shared server cache according to whichever request arrived last. Concurrent Arabic and English requests must not share mutable per-request direction state.
Radix Primitives' Direction Provider supplies reading direction to its primitives. Configure it from the same resolved UI value, and retain HTML direction for the application's DOM and CSS. A library provider and a native attribute serve related but separate purposes.
Test the component rather than inferring support from its package name. Open a select, use a horizontal tab list with the keyboard, inspect a slider, and dismiss a popup. Confirm that its labels, focus behavior, placement, and visual movement agree with the documented interaction model.
Keep this setup version-specific. Copying a plugin name or provider pattern from an older project can produce a partially configured application. Use the library's current documentation for the version in the lockfile and verify the generated result.
Isolate values when JSX inserts them into Arabic text#
React rendering does not create bidi isolation around interpolated values. Escaping a string for HTML and preserving its visual order are different tasks.
The sample reference in this notebook is 2874-TEA. It is an identifier with a fixed group order, not a range. After an Arabic label, its digits-first shape is a bidi hazard.
Problem
export function TastingReference({ reference }) { return <p>مرجع العينة: {reference}</p>;}Better
export function TastingReference({ reference }) { return <p>مرجع العينة: <bdi dir="ltr">{reference}</bdi></p>;}Render it with reference="2874-TEA" under the Arabic boundary. The known LTR identifier receives its own isolated run. For a user-authored name whose direction is unknown, a separate <bdi> can determine direction from its contents instead.
W3C's inline bidi guidance explains why boundaries belong around the inserted phrase. A plain <span> is not an isolation fix. Avoid forcing the entire Arabic paragraph to LTR to preserve one identifier.
For full translated sentences, use your localization library's rich interpolation support to retain the boundary while allowing translators to place the value appropriately. The snippets focus on bidi behavior and contain Arabic text directly for clarity. See Arabic and English mixed text for the broader text rules.
Preserve drafts when the interface locale changes#
Changing the interface language should not silently discard an unsaved tasting note. Inspect keys and component identity before treating a locale switch as a harmless rerender.
A pattern such as key={locale} on the notebook workspace intentionally remounts that subtree when the locale changes. If the note lives in local component state, that remount can reset it. React's state preservation guidance explains how tree position, component type, and keys affect this behavior.
Keep draft state in an owner that survives the intended language switch, or persist and restore it explicitly. Reset locale-dependent derived output without resetting the user's content unless that is the specified interaction. Selected sample identity should likewise survive by stable record key rather than translated title.
Check memoized formatters and callbacks. A formatter created from the initial locale can keep producing the old digit convention if its dependencies never change. A notification callback can similarly retain an old translated string. Derive these from the current configuration and include the relevant reactive dependencies.
Exercise the switch with a draft entered, a popup open, and a request pending. Verify the eventual content, not only the heading immediately after the switch. A late response must not restore an obsolete locale or replace a newer selection.
Give inputs and formatting their own content policy#
The interface's direction is the default, not a rule that every value must be RTL. A tasting-note textarea can accept Arabic or English prose; a sample code, URL, or email field has a different content contract.
For free text, decide whether the field should follow the interface or use dir="auto" from the entered content. Test empty, Arabic-leading, Latin-leading, and digits-only values. Direction detection is not language detection, and a field's placeholder is not a dependable way to determine the entered value's direction.
Keep labels associated with controls in repeated components. React's useId can generate IDs for htmlFor and descriptive relationships; use data-derived keys for records rather than those generated IDs. Repeated notebook cards should not all point their labels at the first textarea.
Use locale-aware formatting for displayed values while preserving numeric data for calculations. Set the intended numbering system and, for dates, calendar and timezone when those choices affect output. Translate complete plural messages rather than combining a formatted count with one noun form.
Review long Arabic notes at the real panel width. Direction does not prevent clipping, missing font coverage, or insufficient line spacing. Link those failures to the owning text styles; Arabic text overflow covers the layout diagnosis.
Verify the DOM, interaction, and server response separately#
Start with the initial response for both supported locales. Inspect the document's lang and dir, the resolved UI data, and hydration warnings. Check direct navigation and refresh, including an Arabic route opened without a prior English visit.
At the component level, inspect the rendered host element rather than only React DevTools props. Confirm that the wrapper forwarded attributes, logical CSS resolves on the intended edge, and a nested LTR surface is scoped correctly. A DOM assertion can establish an attribute; it cannot prove a menu's arrow-key behavior or that text is visually unclipped.
Open portal-mounted surfaces and inspect their actual ancestors. Exercise library controls with a keyboard and pointer, including boundaries and disabled states. Include the empty notebook, a loading failure, and a long mixed-direction note, so conditional branches are reviewed as well as the populated page.
Finally, switch locale while editing and while a preview remains open. Confirm that drafts, record identities, and focus remain appropriate, while labels, formatters, providers, and direction update together. Use browser-based interaction and visual checks for those outcomes; server-rendered markup snapshots cover only part of them.
A free Ritla scan can report document direction missing, contradicted, or declared only in CSS and Direction-sensitive physical properties without an RTL override in the rendered React interface. For the next integration problem, see dir versus CSS direction and debugging RTL layout problems.