How to add RTL support to React
Follow a migration path for adding Arabic RTL to an existing React app, covering document direction, shared styles, icons, libraries, and tests.
By Omran Khleifat, Founder of Ritla
Guide13 min read
Adding dir="rtl" to an existing React app reveals which parts already follow browser direction and which parts encode English layout assumptions. A normal flex row may move into place while its physical margins, navigation arrows, and portal-mounted menu remain wrong. Fixing individual screens before establishing that boundary makes each screen accumulate its own exceptions.
Work in a sequence: establish document direction from the active locale, migrate shared directional styles, review navigation artwork, configure libraries and portals, then verify components in both directions. Keep English as a regression target throughout the migration.
The example product is a fictional choral-score annotation workspace. Its Arabic interface needs to adapt, while imported score pages, titles, and musical content keep their own presentation rules. That distinction prevents a layout migration from reflecting the content users came to annotate.
1. Map one complete workflow before changing shared CSS#
Choose a representative route through the existing application. For the score workspace, start in the library, open a score, add an annotation, and open its sharing surface. Include the compact layout, an empty library, a loading state, and a failed save.
Record which components own the shell, action groups, overlays, and notifications. Identify where each actually renders in the DOM. A sharing panel declared under a score page in JSX may be inserted under the document body by a component library.
| Surface | Direction decision to record | Evidence to keep |
|---|---|---|
| Document and app shell | Which locale supplies lang and dir? | Initial HTML and rendered root attributes |
| Library card | Which edge owns the open action? | English and Arabic layout at the same width |
| Annotation editor | Which content direction does the field support? | Empty and populated editing states |
| Sharing surface | Where does it mount and get direction? | Open overlay, focus, and placement |
| Score canvas | Which geometry belongs to imported content? | Content orientation and pointer behavior |
| Save notification | Which host, placement, and animation are used? | Entrance, resting position, and dismissal |
This inventory keeps the first migration slice concrete. Do not begin by replacing every occurrence of left in the repository. Some uses describe physical coordinates or intentional content behavior. Others are generated by dependencies and need configuration at their source.
Capture the existing English behavior before changing shared primitives. Keep the same data, container width, and interaction state for comparisons. A later Arabic screenshot with different content cannot establish whether a spacing change preserved English.
Trace each directional assumption to its source. Search authored CSS for physical margins, padding, borders, positioning, floats, alignment, transforms, and reversed rows. Search JavaScript and JSX for their camel-cased inline-style equivalents too. Include icon adapters and component-library wrappers; searching stylesheets alone misses configuration and geometry calculated in code.
Treat search results as an inspection queue. A physical coordinate supplied by a pointer API is different from padding intended to precede a label. Classify each result as a relationship to convert, a physical behavior to preserve, or a dependency behavior to configure. Record that reasoning beside the owning component or migration task.
Follow generated styles back to their source before changing them. A declaration visible in DevTools may come from a theme token, a utility class, or an RTL processing pipeline. Editing generated output will not establish a durable fix and can leave the next build behaving differently from the reviewed page.
2. Establish document direction before the first display#
Resolve one supported interface locale and derive its direction from an explicit application policy. This helper supports the example application's two choices:
export function scoreLocale(locale) { switch (locale) { case 'ar': return { locale: 'ar', lang: 'ar', dir: 'rtl' }; case 'en': return { locale: 'en', lang: 'en', dir: 'ltr' }; default: throw new Error('Unsupported score interface locale'); }} export function applyScoreDocumentLocale(locale) { const ui = scoreLocale(locale); document.documentElement.lang = ui.lang; document.documentElement.dir = ui.dir; return ui;}applyScoreDocumentLocale is browser-only. For a client-rendered app, call it with the resolved locale in the bootstrap path before rendering the localized interface. Then use that same locale for messages and component configuration. React's createRoot documentation describes the client-rendering entry point.
For server rendering, use the pure scoreLocale helper to emit the attributes through the framework's root document or layout. Do not call the browser-only function on the server. Supply the same initial locale to the client, rather than rendering English first and waiting for an effect to select Arabic.
React's hydrateRoot contract expects matching initial server and client output. Fix disagreement at the locale source; suppressing hydration warnings does not configure direction or guarantee that mismatched attributes are repaired.
Set both attributes for their separate purposes. lang="ar" declares language; dir="rtl" establishes direction. W3C's structural direction guidance recommends the document boundary for a full RTL page. Use local boundaries for genuinely embedded or differently directed surfaces, not as substitutes for a missing document setting.
3. Check that shared React wrappers preserve the boundary#
A custom component does not automatically forward every prop to its DOM output. Inspect the app shell, panel primitives, and styled wrappers before assuming that a dir prop reaches the element that needs it.
For each wrapper, identify whether direction should be inherited or explicitly supplied. If a component accepts dir and lang, forward them to its intended root. If it renders several separate surfaces, decide which surfaces need the values rather than attaching attributes to an unrelated container.
Inspect the actual DOM as well as React DevTools. A correct prop on a React component is not evidence of a correct HTML attribute. Similarly, a direction value in React context does not modify the DOM unless a consumer applies it.
Avoid making every leaf component mutate the document root. The application shell should own that document-wide state. A separately embedded annotation widget should own its own boundary so mounting it does not change the surrounding host page.
Test inheritance through an ordinary panel and through an intentional nested LTR surface. A selector such as [dir="rtl"] .control can still match a control inside an intervening LTR boundary. MDN's :dir() documentation explains how semantic direction selectors differ from ancestor attribute selectors and CSS-only direction.
4. Migrate shared spacing without changing the English design#
Start with the primitives used by the chosen workflow. Convert one directional relationship at a time, verify both languages, then reuse the corrected primitive elsewhere.
This score card has a title followed by its open action. The caller supplies the title's known language, destination, and translated action label:
export function ScoreCard({ title, titleLang, href, openLabel }) { return ( <article className="score-card"> <h2 className="score-card__title"> <bdi lang={titleLang}>{title}</bdi> </h2> <a className="score-card__action" href={href}>{openLabel}</a> </article> );}The existing LTR design uses available space before the action to push it toward the row's end.
Problem
.score-card { display: flex; align-items: center; flex-wrap: wrap; gap: 0.875rem;} .score-card__title { min-inline-size: 0; overflow-wrap: anywhere;} .score-card__action { margin-left: auto;}The physical margin retains its left-side meaning after the row becomes RTL. It no longer expresses “space before this action in the reading sequence.”
Better: retain the card and title rules, replacing only the action rule:
.score-card__action { margin-inline-start: auto;}English keeps its original left auto margin. Arabic gets the corresponding right auto margin, allowing the action to sit at inline end. MDN documents margin-inline-start and its mapping through writing direction.
Check the wrapping state separately. Once the action occupies another flex line, its placement still needs to match the compact card design. Logical properties express direction; they do not decide the desired responsive composition.
Review padding, borders, text alignment, and positioning using the same method. React inline styles use names such as marginInlineStart; CSS Modules retain ordinary CSS property semantics. See converting LTR CSS to RTL for a wider audit.
Inspect the winning declaration after the change. Replacing a rule in the component stylesheet does not establish that the browser uses it: an inline style, responsive override, or utility class may still supply a conflicting physical value. Check the computed margins on the action in both directions, and use DevTools to identify which declaration supplies each side.
Review shorthands as well as individual properties. A later margin rule can replace spacing that the logical longhand was intended to establish. Keep one clear owner for the action's alignment rather than retaining an old physical declaration and adding several stronger RTL selectors above it.
Test the English route again after removing those conflicts. A fix that depends on a highly specific Arabic selector can conceal an incorrect shared default. Prefer a shared logical rule when the underlying relationship is the same in both languages, and reserve directional overrides for behavior that actually differs.
5. Remove workarounds that reverse the sequence twice#
Changing document direction can expose older layout patches. A wrapper using row-reverse to place English items on the right may now make an Arabic row run left to right. A reversed records array can similarly fight the layout's own direction handling.
Keep source order tied to the task. The score title and its open action remain those same items; the library's chronological or user-selected sort remains the same sort. Direction changes how the layout occupies the interface, not which record is next in the dataset.
Do not fix focus order with positive tabIndex values after rearranging the visual layout. Correct the component's source and layout relationship, then verify keyboard movement through it. An interface that appears ordered but focuses controls in a conflicting sequence still needs work.
Audit drag-and-drop, resizable panels, and virtualized collections separately. These components may calculate coordinates or item positions outside CSS layout. Record whether their API uses physical left/right, inline start/end, or an explicit RTL option. Do not apply a second reversal after the library already accounts for direction.
If the desired Arabic ordering genuinely differs, model that as a product ordering decision with stable record identities. Do not bury it in a component's isRtl styling branch. RTL flexbox covers the browser behavior behind these doubled reversals.
6. Adapt directional artwork and motion deliberately#
Review back, forward, open-detail chevrons, and sequence controls. In an Arabic navigation flow, back points right and forward points left. Material Design's bidirectionality guidance describes that navigation convention.
Choose one implementation owner: select finished directional assets in the icon adapter, or reflect canonical artwork at the control. Do not select an RTL asset and also apply an application reflection. Verify the rendered result instead of relying on an asset name such as BackIcon or ArrowLeft.
Keep imported score pages unchanged unless their content presentation explicitly calls for another orientation. A navigation arrow between interface screens and a notation mark inside an imported score are different kinds of content. Reflecting the entire score viewer would alter the content as well as the controls.
Inspect animations independently. translateX remains a physical horizontal translation; changing document direction does not change the sign of its offset. Review where a panel enters, its final position, and its exit. A correct resting screenshot can conceal movement through the wrong edge.
Avoid global rules that transform every SVG or the entire application wrapper. They can reflect lettering, logos, and content geometry while appearing to repair one chevron. Define the expected behavior for the control, then adapt only the relevant artwork or motion. What to mirror in RTL helps separate those decisions.
7. Configure libraries and open their portalled surfaces#
After the shared native layout behaves correctly, configure each dependency's directional layer. Keep the HTML attributes in place; a theme or provider supplements them rather than replacing them.
For Material UI, use the installed version's RTL setup. The documented setup separates HTML direction, theme direction, and RTL style processing. Follow the styling-engine path used by the application and keep its server style integration consistent with that choice.
For Radix Primitives, its Direction Provider supplies direction to primitives that consume it. Configure it from the same locale policy. A provider does not rewrite all application CSS or translate the component's labels.
Document which styles pass through an RTL processor and which are delivered unchanged. A migration can combine logical application CSS with a library's configured style pipeline, but it should not leave developers guessing whether a physical declaration has already been rewritten. Inspect the generated declaration when its behavior disagrees with the source.
If the application previously shipped separate LTR and RTL stylesheets, establish which one remains authoritative while migrating shared primitives. Loading both without a defined cascade can make import order decide direction. An apparently corrected English route may still be using stale RTL output after a language switch.
Keep style caches and theme configuration aligned with the selected direction. For server rendering, avoid mutating one process-wide direction setting according to the current request. Exercise concurrent requests for both locales in the integration that generates the styles, then verify each response independently. Static component markup tests cannot establish that the correct style output accompanied that markup.
Open the menu or dialog before declaring the integration complete. React portals preserve React-tree relationships such as context while changing where nodes live in the DOM. Browser direction inheritance follows the actual DOM ancestors.
If the whole document is RTL, a body-mounted portal may inherit correctly. If Arabic exists only inside an embedded workspace, a popup mounted outside that boundary needs direction at its actual rendered surface or another supported library boundary. Setting dir on an ancestor that the portal escapes does not establish that inheritance.
Verify keyboard navigation, focus return, popup placement, translated close labels, and nested submenus. An RTL trigger button does not prove that its expanded surface uses the same direction. Record any deliberate component exceptions so later wrapper changes do not remove them accidentally.
8. Add text boundaries where components insert variable values#
The score workspace uses references such as 6739-REED. A fixed identifier must retain its group order inside Arabic text. React interpolation does not establish a bidi boundary automatically.
export function ScoreReference({ label, reference }) { return <p>{label}: <bdi dir="ltr">{reference}</bdi></p>;}For the Arabic fixture, pass label="مرجع النوتة" and reference="6739-REED". The value's digits-first shape needs isolation after Arabic text. Keep the label in the translation catalogue; the component here demonstrates the value boundary.
For arbitrary score titles, the card's separate <bdi> lets that run determine its own direction. Tag a known title language with lang, as the fixture below does, without treating language tagging as a substitute for direction. W3C's inline bidi guidance explains these boundaries.
Classify editing fields by their expected content. An annotation textarea accepting prose can follow the interface or use a deliberate dynamic-direction policy. A URL or email field needs a different rule. Do not add dir="rtl" to every input as part of a bulk migration.
Keep translation and formatting work visible in the migration inventory. Actions, placeholders, validation messages, and notifications all need Arabic copy. Numbering systems, calendars, and timezones need explicit product choices when their output matters. Direction alone cannot complete that work; use Arabic localization testing for the message review.
9. Create paired fixtures before expanding the migration#
Use a small fixture that can render the same corrected primitive in both directions. Put this fixture, the earlier ScoreCard, and the pure scoreLocale helper in ScoreCardFixture.jsx, exporting the fixture for the example test:
export function ScoreCardFixture({ locale }) { const ui = scoreLocale(locale); return ( <div lang={ui.lang} dir={ui.dir}> <ScoreCard title="Morning Canopy" titleLang="en" href={`/${ui.locale}/scores/morning-canopy`} openLabel={ui.locale === 'ar' ? 'فتح النوتة' : 'Open score'} /> </div> );}The English score title is intentional fixture content and remains the same record in both interfaces. The surrounding action is translated. The application routes shown are examples; use actual localized destinations in the real workspace.
In a Node-based test pipeline that compiles JSX, this test verifies the boundary and action label:
import assert from 'node:assert/strict';import { renderToStaticMarkup } from 'react-dom/server';import { ScoreCardFixture } from './ScoreCardFixture.jsx'; for (const [locale, direction, label] of [ ['en', 'ltr', 'Open score'], ['ar', 'rtl', 'فتح النوتة']]) { const html = renderToStaticMarkup(<ScoreCardFixture locale={locale} />); assert.ok(html.includes(`dir="${direction}"`)); assert.ok(html.includes(`lang="${locale}"`)); assert.ok(html.includes(label)); assert.ok(html.includes(`href="/${locale}/scores/morning-canopy"`));}renderToStaticMarkup produces noninteractive HTML. This test catches missing fixture attributes and incorrect labels or destinations. It does not prove that the auto margin resolves on the intended edge, the link can be used with a keyboard, or a title is visually unclipped.
Add browser checks for those outcomes using the real stylesheet and route. At a wide width, compare title and action positions in each direction. At a narrow width, inspect wrapping and available space. Then activate the action and confirm the destination, including modified link clicks where supported.
Use the same paired-fixture pattern for the next shared primitive rather than waiting until the entire application has been converted. Keep text, geometry, and interaction assertions separate enough that a failure identifies which contract broke.
Also place an RTL fixture and an LTR fixture on the same browser test page. This reveals rules that depend on an outer Arabic ancestor and override an inner LTR boundary. Keep each fixture's labels and destinations associated with its own locale so a page-wide language switch is not required to compare them.
Include a long title and a longer translated action in the browser fixture. Measure whether the complete control remains within the card, then check its focus indication and activation. A test that merely finds the title in the DOM can pass while the action is clipped or covered. Keep a short-title case too, because auto spacing and wrapping follow different paths as available space changes.
10. Review stateful behavior before exposing the Arabic route#
Test direct navigation to the Arabic workspace, refresh, and switching from English without a reload. Confirm that the initial document, messages, library providers, and rendered components use the same interface configuration.
Switch while an annotation draft exists and while the sharing surface is open. A locale-dependent key on the entire workspace can remount it and discard local state. Preserve the intended draft and selected score identity, and update derived labels and direction without resetting unrelated work.
Exercise loading, empty, permission-denied, and failed-save branches. A populated library does not show whether their fallback components forward direction or contain untranslated actions. Repeat with long Arabic annotations and mixed-direction titles, including after fonts finish loading.
Check at the layout widths the workspace actually encounters, including an open inspector and browser zoom. Inspect the complete surface rather than treating the absence of a horizontal scrollbar as proof that nothing is clipped or outside the visible area. Use testing RTL across breakpoints when narrowing the remaining failures.
Expand to other routes through the shared components that have passed both-language review. Keep a record of unresolved direction assumptions and the surface that owns them. A local exception should explain a real content or interaction requirement, so future CSS cleanup can distinguish it from an unfinished migration.
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 migrated React interface. For a remaining migration failure, use debugging RTL layout problems and converting LTR CSS to RTL.