Material UI RTL guide
Configure Material UI document direction, theme and Emotion cache for Arabic, then debug portals, custom styles, inputs and language switches.
By Omran Khleifat, Founder of Ritla
Guide13 min read
A Material UI text field can read Arabic from the right while its floating label and outline still use left-to-right styling. A dialog can receive the Arabic theme but inherit English document direction. Both look like incomplete mirroring, but they fail at different boundaries.
Material UI RTL support coordinates HTML direction, the component theme and the styling engine. None of those settings translates application content, and a styling plugin cannot rewrite every external stylesheet or inline style in the product.
This guide configures the default Emotion-based Material UI setup, then follows a makerspace printer-reservation interface through the failures that remain. The examples use the current RTL package and TextField slot APIs. Match them to the installed Material UI major version rather than combining them with an older JSS setup.
Diagnose document direction, theme and style output separately#
The settings have different jobs:
| Layer | What it controls | Evidence to inspect |
|---|---|---|
HTML dir | Browser direction and inheritance | Document attributes and computed direction |
Theme direction | Direction supplied to MUI component logic | The active theme at the failing component |
| Styling engine's RTL transformation | Direction-sensitive generated CSS | Injected stylesheet declarations |
| Locale text and application translations | Labels and messages | Visible text and accessible names |
An Arabic page should declare its language and direction in the document:
<html lang="ar" dir="rtl">The W3C document-direction guidance explains why this belongs in HTML. Setting lang="ar" does not supply direction, and a theme object does not edit the document's attributes for you.
Inspect the direct response as well as the final interactive page if the application renders on the server. A late browser update can make a screenshot look correct while concealing an incorrect initial document. covers document direction missing, contradicted, or declared only in CSS.
Next inspect the provider that reaches the failing component. A nested theme or cache provider can change its environment even when the application's outer configuration is correct. Check the provider tree and the generated style tags before adding component-specific overrides.
Keep an English comparison using the same reservation state. That separates a shared styling defect from a direction-dependent one. A disabled button, a focused field and an open dialog are different states and should not be substituted for one another during diagnosis.
Record the failing element rather than describing the whole page as reversed. In browser developer tools, select the native input, its label and its surrounding control separately. Read computed direction on each, then find the stylesheet rule responsible for the misplaced margin, transform or alignment. The winning declaration and its source tell you whether to investigate browser inheritance, generated MUI CSS or an application override.
Changing text-align temporarily is a useful diagnostic only if you undo it afterwards. It can move text inside a box without correcting the component's theme or the label's generated geometry. Likewise, seeing direction: rtl in the computed-style panel establishes the element's browser direction; it does not establish which theme or cache produced its stylesheet.
Configure the Emotion cache and theme together#
In a project already using Material UI with its default Emotion dependencies, add the cache and RTL transformation dependencies if they are not present:
npm install @emotion/cache stylis @mui/stylis-plugin-rtlThe current Material UI RTL documentation uses @mui/stylis-plugin-rtl. Check package compatibility when updating an older integration instead of assuming every similarly named plugin is interchangeable.
This provider module is a browser-rendered React example. It prepares separate configurations for the two directions:
// DirectionProviders.tsximport type { ReactNode } from 'react';import { CacheProvider } from '@emotion/react';import createCache from '@emotion/cache';import { ThemeProvider, createTheme } from '@mui/material/styles';import { prefixer } from 'stylis';import rtlPlugin from '@mui/stylis-plugin-rtl'; type Direction = 'ltr' | 'rtl'; const caches = { ltr: createCache({ key: 'mui-ltr', stylisPlugins: [prefixer] }), rtl: createCache({ key: 'mui-rtl', stylisPlugins: [prefixer, rtlPlugin] }),};const themes = { ltr: createTheme({ direction: 'ltr' }), rtl: createTheme({ direction: 'rtl' }),}; export function DirectionProviders({ direction, children }: { direction: Direction; children: ReactNode;}) { return ( <CacheProvider value={caches[direction]}> <ThemeProvider theme={themes[direction]}> {children} </ThemeProvider> </CacheProvider> );}Mount the Arabic application beneath DirectionProviders with direction="rtl", and set its document attributes to Arabic and RTL through the application's document layer. The provider deliberately does not infer language from text or mutate the document during rendering.
Keep these browser cache instances stable instead of creating a new cache on every component render. Their distinct keys identify the separate style namespaces. The Emotion cache reference documents the key and preprocessing options.
Inspect the generated data-emotion style tags when the provider path is uncertain. Compare their cache keys with the selected configuration, then inspect the actual declaration involved in the failure. A key is a breadcrumb, not proof that every component uses the intended plugin list. A nested provider or a separately mounted widget can introduce another cache, and plain inline styles will not appear in those generated rules.
The prefixer is included explicitly because supplying custom stylisPlugins replaces the default plugin list. Adding only the RTL plugin can therefore remove prefixing that the application previously received. Keep the documented order, with prefixing before RTL transformation.
Do not apply this module-level browser-cache lifetime unchanged to server requests. Server rendering needs request-scoped cache handling, covered below. Immutable theme configuration and a cache that records inserted styles are different kinds of state.
If the project uses styled-components, configure the engine MUI actually uses. An Emotion cache cannot transform styles generated by another engine. MUI's styled-components integration documents the engine replacement; the RTL guide shows its StyleSheetManager configuration. Treat that as an alternative integration, not a second provider to stack onto the Emotion example.
Verify an outlined field before styling the whole page#
Start with a small component under the configured providers:
import { Stack, TextField, Button } from '@mui/material'; export function ReservationProbe() { return ( <Stack spacing={2} sx={{ p: 3, maxWidth: 480 }}> <TextField id="printer-project" label="عنوان المشروع" defaultValue="نموذج حامل الكتب" helperText="اكتب اسماً يساعد المشرف على تمييز الحجز." variant="outlined" /> <Button variant="outlined">مراجعة حجز الطابعة</Button> </Stack> );}This is a layout probe; connect the button to the application's reservation action when integrating it. Inspect the input text, floating label, outline notch, helper text and button together. Changing only text alignment can make one part look right while another still reflects a missing configuration layer.
Test the field empty, filled and focused. A floating label occupies a different state from an empty label, so a screenshot of one does not validate the other. Add an Arabic validation message and verify that it stays associated with the field without colliding with the next control.
If the text is RTL but the label geometry is wrong, compare the active theme and injected CSS. If both the text and helper text remain LTR, inspect DOM direction and local overrides too. If the isolated probe works but the reservation page fails, inspect the extra providers and style overrides introduced by that page.
Avoid compensating with a manual label translation or a hard-coded notch position before tracing the configuration. Those adjustments can produce a second correction when the missing RTL transformation is later restored.
Use the TextField documentation for the component's states and structure. Keep the reproduction on the same component variant, size and theme as the failing product field.
Repeat the probe at the reservation panel's smallest supported width, with the production font and a longer helper message. Look for the label touching the outline, helper text being cut off, or a neighboring action covering the message. These are different failures from incorrect direction. Fixing the provider configuration does not establish that the component has enough space for translated content. Remove fixed heights or investigate the responsible width constraint before shrinking Arabic text to conceal the collision.
A portal keeps React context but changes DOM ancestry#
A dialog opened inside an Arabic preview can appear under an LTR document body. The React component is visually associated with its trigger, but the dialog's DOM is not necessarily inside the trigger's wrapper.
This distinction explains a misleading symptom: the dialog can receive the intended theme and Emotion cache through React context while missing the wrapper's inherited dir. React's portal documentation explicitly distinguishes physical DOM placement from React ancestry and context.
When direction is declared globally on html, ordinary portal content can inherit it from the document. When Arabic direction is local to a preview or embedded region, put direction on the portaled component too:
import { useState } from 'react';import { Box, Button, Dialog, DialogTitle, DialogContent, DialogActions,} from '@mui/material'; export function PrinterBookingDialog() { const [open, setOpen] = useState(false); return ( <Box dir="rtl"> <Button onClick={() => setOpen(true)}>عرض شروط الحجز</Button> <Dialog dir="rtl" open={open} onClose={() => setOpen(false)} aria-labelledby="printer-booking-title" > <DialogTitle id="printer-booking-title">شروط حجز الطابعة المجسمة</DialogTitle> <DialogContent>أرفق ملف المشروع قبل إرسال الحجز إلى المشرف.</DialogContent> <DialogActions> <Button onClick={() => setOpen(false)}>العودة إلى الحجز</Button> </DialogActions> </Dialog> </Box> );}Render this beneath the RTL providers. To reproduce the local-direction failure, keep the document LTR and remove only the dialog's dir prop. The Arabic wrapper alone does not establish the dialog's DOM ancestry. MUI documents this portal case in its RTL setup guidance; the Dialog API describes the component props.
Inspect the open dialog in the rendered DOM, not just its JSX location. Then test its title, content, actions, focus entry, closing and focus return. Repeat on a narrow viewport with the longest actual dialog title.
Apply the same ancestry investigation to menus, tooltips, popovers and autocomplete popups. Use each component's documented props or slot configuration to reach the relevant rendered element. Do not assume that a direction prop on the trigger reaches every popup.
Disabling a portal solely to inherit a wrapper's direction changes more than direction. It can alter clipping and stacking relationships. Make that placement decision deliberately rather than using it as the first RTL repair.
Distinguish generated styles from inline and external CSS#
The RTL styling plugin processes CSS generated through its configured engine. It is not a browser-wide rewrite of every style associated with a MUI component.
The reservation queue might contain this custom spacing:
import Box from '@mui/material/Box'; export function BookingSummary() { return <Box style={{ marginLeft: '26px' }}>الحجوزات بانتظار المراجعة</Box>;}That style value is an inline physical margin. React applies it to the DOM; it does not pass through Emotion's stylesheet preprocessing. The React DOM style reference describes this prop.
If the margin means indentation from reading start, express that relationship in the same style boundary:
import Box from '@mui/material/Box'; export function BookingSummary() { return <Box style={{ marginInlineStart: '26px' }}>الحجوزات بانتظار المراجعة</Box>;}The English side stays left; horizontal RTL maps the margin to the right. The CSS Logical Properties specification defines that mapping. Check the element's own direction when it sits inside locally different-direction content.
For custom styles written with MUI's sx prop or Emotion's styled, inspect the CSS emitted by the active cache. Physical declarations on that path can already be transformed. Manually swapping them in a direction branch as well can express the wrong side after preprocessing.
Also preserve units when moving styles between APIs. MUI's sx reference documents theme-aware values: a numeric spacing shorthand is not necessarily the same measurement as a numeric React inline style. Use an explicit CSS length when the repair must preserve the existing size exactly.
External stylesheets and CSS Modules need their own direction strategy. A correct MUI button does not establish that a neighboring custom panel has logical padding or a matching border edge. covers direction-sensitive physical properties without an RTL override. Trace the source of the declaration before deciding which layer should fix it.
Check style injection order when a custom override loses. MUI's interoperability guide discusses cache placement and precedence. Correct direction and correct precedence are separate requirements.
For a stubborn override, temporarily disable its winning declaration in developer tools. If the standard component immediately returns to the expected geometry, keep the investigation on that override rather than changing the global theme. Check both the base rule and its focus, error and breakpoint variants. An RTL repair on the default state can still lose to a later physical declaration that activates only when the reservation field is focused or the side panel becomes narrow.
Opt out of flipping only for an intentional physical coordinate#
A printer-layout preview may contain an annotation measured from the image's physical left edge. That position should not change merely because its surrounding reservation interface becomes Arabic.
For a declaration emitted through the RTL styling engine, MUI documents a @noflip directive in template-literal styles:
import { styled } from '@mui/material/styles'; export const PreviewAnnotation = styled('div')` position: absolute; /* @noflip */ left: 26px;`;Render the annotation inside the preview's positioned container. The preserved left coordinate belongs to that preview, not the page's reading sequence. Test it against the same feature in the image in both language modes.
Keep the comment in the generated CSS template syntax shown. A JavaScript comment beside an object property is not the same directive reaching the style processor. Inspect the emitted rule when introducing an exception.
Do not use a flipping exception to solve the direction of Arabic text, and do not assume local dir="ltr" turns off the RTL cache. The DOM direction and the cache's preprocessing remain separate settings. If an embedded English region needs its own component behavior, decide its theme, styles and DOM direction together.
Likewise, a directional icon and a physical diagram have different meanings. Theme direction does not make every custom SVG appropriate for the surrounding sequence. Review arrows against the action they advance; use what should be mirrored in RTL for the distinction.
Keep technical input values LTR without moving the whole field#
The reservation form can have Arabic labels around an email field. Setting LTR direction on the entire TextField changes the direction boundary for more than the typed value.
With the current slot API, target the native input:
import TextField from '@mui/material/TextField'; export function BookingContact() { return ( <TextField id="booking-contact" type="email" label="البريد الإلكتروني لصاحب الحجز" autoComplete="email" fullWidth slotProps={{ htmlInput: { dir: 'ltr' } }} /> );}Keep this component in the Arabic theme, cache and surrounding document direction. The native input receives the technical-value direction, while the label and field geometry remain part of the Arabic component context.
slotProps.htmlInput targets the HTML input; slotProps.input targets MUI's Input component. The TextField API and component documentation distinguish those slots. Check the API for the installed major when maintaining an older application.
Inspect the actual input element and test typing, selection and editing. Include an empty field, an existing value, an error and the focused label. Do not force every Arabic text field to LTR simply because this email field requires it. covers telephone, email and URL inputs rendered RTL; ordinary Arabic input has a different contract.
Adornments also need inspection in the rendered field. Their placement, surrounding text direction and accessible label are separate from the input's direction. Use Arabic form UX when the issue extends into field-specific behavior or validation.
Translate component text and configure Arabic typography separately#
Theme direction changes layout behavior. It does not translate a confirmation button, an accessible label or a pagination message.
MUI supplies locale objects for supported component text. For example, when Egyptian Arabic matches the product's locale choice:
import { createTheme } from '@mui/material/styles';import { arEG } from '@mui/material/locale'; export const localizedArabicTheme = createTheme({ direction: 'rtl' }, arEG);Use that theme in the Arabic entry of the earlier provider configuration. Choose the appropriate supported locale for the product, and review the translated wording rather than treating one regional object as the definition of all Arabic. The MUI localization guide lists available locales and explains customization.
Application-owned project titles, booking actions and validation messages still need the application's translation system. Inspect icon-button names and helper text along with visible headings.
MUI X packages have additional localization configuration. The Data Grid localization guide covers its component text. Date pickers distinguish translated interface labels from date-library formatting settings. A translated picker button is not evidence that displayed dates follow the intended locale.
Configure an Arabic-capable font through the theme's typography settings, and load it through the application's font mechanism. MUI's typography customization guide covers the theme configuration. A family name in a theme does not itself deliver the font file.
Inspect rendered glyphs, requested weights, letter spacing and line height on the actual Typography variants, buttons and labels. Do not assume one body setting supplies every component's metrics. Test a multiline helper message and a long dialog title after the font has loaded. covers Arabic falling back past the declared family; a fully mirrored component can still have that typography failure.
Keep language switching and server rendering consistent#
When switching languages, update the document direction, active theme and cache selection from one resolved locale. The provider example accepts a direction explicitly so that these decisions can share the same source.
Do not keep an RTL styling cache while selecting an LTR theme and changing only the document attribute. That can leave browser flow, component logic and generated CSS disagreeing. Use stable, separate browser configurations and select the matching pair.
Test switching with a dialog open and with a field containing unsent project notes. Decide which transient states should close, reset or remain. Remounting the whole application may hide stale direction state while also discarding the user's work.
For server rendering, create a fresh Emotion cache per request and deliver the corresponding generated styles. MUI's server-rendering guide describes that lifecycle. Keep the initial client direction and cache configuration consistent with the server's result, and investigate hydration warnings or a visible direction change on load.
Next.js applications should use MUI's version-matched framework integration, including the appropriate cache collector for the router. Adapt that integration's cache configuration rather than adding an unrelated inner cache that receives styles outside the collector's intended path. Configure plugin functions in the appropriate integration module instead of passing them through an unsupported server/client boundary.
Check the Arabic route directly, refresh a deep link and switch from English. Repeat requests in both language orders. Compare the initial document and CSS with the hydrated page. A client-side toggle demonstration alone does not verify the first deployed response.
Include a cold load with an empty browser cache. A development session that already visited both languages can retain styles that disguise an incomplete first response. Save the initial HTML, note its direction and style keys, then compare it with the DOM after hydration. If the first paint is wrong and the later page is right, investigate the server's locale resolution and style collection before adding a browser-only correction.
Exercise back and forward navigation too. The visible route, document language and selected provider configuration should agree after navigation restores an earlier reservation page. Keep a populated field and an open overlay in this test so that it also exposes components whose local state survives the change. Capture the failing navigation sequence alongside the resulting screenshot; a screenshot alone cannot show which earlier language supplied the stale configuration.
Verify the configured components and their exceptions#
Use the reservation probe, open dialog, email field and preview annotation as separate checks. Each exercises a different boundary, so one passing screenshot cannot stand in for the rest.
- Inspect document attributes, the active theme and generated CSS independently.
- Check empty, filled, focused, disabled and error states on the actual TextField variant.
- Open portals and inspect their DOM direction, focus behavior and narrow-screen layout.
- Compare custom inline styles with styles generated through the RTL engine.
- Switch languages without losing or mislabeling the reservation's current state.
- Verify the same journeys against a production build and its first server response.
When a failure remains, save the provider path, rendered element, winning declaration, locale and interaction state. If only one custom panel fails while standard MUI fields work, trace that panel's style source before rebuilding the global RTL setup.
A free Ritla scan of the Arabic reservation page can surface contradictory document direction or direction-sensitive physical properties without RTL overrides. Use debugging RTL layout problems to investigate the remaining component boundary, or Arabic text input direction when the field shell is correct but its editable value still behaves incorrectly.