Skip to content

Bidi problems in React applications

Fix mixed Arabic and Latin text in React with isolated values, rich translation placeholders and tests that separate data from display.

By , Founder of Ritla

Guide13 min read

A batch reference arrives from the API as 294805-ORCHID. React state contains that exact string. Copying the activity message returns the same reference. Yet an Arabic activity feed can display its parts as ORCHID-294805.

The data has not necessarily changed. React inserted text into an Arabic paragraph, and the browser resolved the reference together with the surrounding words. A component boundary, JavaScript expression or translation placeholder does not automatically create a bidirectional isolation boundary.

This guide uses an orchid propagation journal: technicians move batches into an incubator and leave bilingual notes. The reference must retain its fixed group order, while the Arabic sentence should continue to read from its normal starting edge. Fix the boundary around the reference before touching the stored value.

Reproduce the failure in an Arabic sentence#

Problem: this component puts a fixed-format reference directly after Arabic text.

jsx
export function BatchTransfer({ batchCode }) {  return (    <p dir="rtl" lang="ar">      نُقلت الدفعة {batchCode} إلى الحاضنة.    </p>  );}

Render it with batchCode="294805-ORCHID". The value begins with digits and ends with Latin letters. In the checked Chromium 151 behavior, this shape after Arabic text displays with the Latin suffix on the other side of the numeric group. An Arabic reader still needs to recognize the manufacturer's reference in its established order; this is an identifier, not a range read from right to left.

Better: keep the same sentence and value, adding a boundary around only the reference.

jsx
export function BatchTransfer({ batchCode }) {  return (    <p dir="rtl" lang="ar">      نُقلت الدفعة <bdi dir="ltr">{batchCode}</bdi> إلى الحاضنة.    </p>  );}

The paragraph remains RTL. The reference receives its known LTR direction and is resolved independently of the surrounding sentence. Isolation works in both directions: the paragraph does not determine the token's internal order, and the token does not pull adjacent punctuation or numbers into its own directional context. W3C's inline bidi guidance explains where to place these boundaries.

Do not reverse the reference in JavaScript, swap its segments in the API response, or switch the entire paragraph to LTR. Those changes alter the wrong layer. A reversed stored value would then be wrong in an English view, an export or a correctly isolated component.

JSX boundaries are not browser text boundaries#

React decides which DOM nodes and text to render. The browser applies text layout to the result. JavaScript variables have no special meaning to the Unicode Bidirectional Algorithm once their contents become text in the page.

These constructions do not isolate a value:

React constructionWhat the browser receives
{batchCode} between text childrenText inside the surrounding paragraph
A component returning batchCodeText, without an isolating element
A fragment around {batchCode}No additional wrapper element
A plain span around {batchCode}An element without a directional boundary

Fragments deliberately avoid adding a DOM wrapper, as React's Fragment reference explains. Giving one a key helps React identify it; that key does not tell the text layout engine anything about direction.

A span is useful for styling or identifying the reference, but a class name alone does not isolate it. Keep the same test value when changing the wrapper. Replacing the digit-first reference with one that starts with Latin letters can make the sentence appear fixed without changing the failing boundary at all.

The underlying algorithm distinguishes strong letters, weak numeric characters and neutral punctuation. Their neighbors affect the resolved order. It does not reverse every character on an RTL page. That distinction is why a digit-first identifier can fail while a Latin-first identifier looks intact. Unicode's Bidirectional Algorithm defines that processing; React does not replace it with another algorithm.

Trace the value before changing the renderer#

Compare the API value, the selector's result, the message component's prop and the rendered reference's textContent. Use the same local fixture at every stage. If a formatter has already swapped the groups before rendering, isolation will faithfully display that incorrect value. Repair the transformation as well as the boundary.

Visual inspection of a console string can be misleading because the console is another text renderer. For a disputed fixture, inspect its code points instead:

js
export function inspectCodePoints(value) {  return Array.from(value, (character) =>    `U+${character.codePointAt(0).toString(16).toUpperCase().padStart(4, "0")}`  ).join(" ");}

Call this helper with the original batch-code string and with the component prop. Matching output rules out a character-level change between those two stages. It also makes otherwise invisible directional characters visible as code-point labels. The helper diagnoses the string; it does not diagnose the resulting glyph positions.

Once the source values match, reduce the rendered context. Keep the Arabic words before the reference while removing unrelated feed controls. Removing all the Arabic text may remove the triggering context and produce an apparent fix. A useful reproduction retains the cause while discarding the surrounding application.

Select isolation and direction separately#

Isolation answers whether adjacent text participates in the value's directional resolution. Direction answers which base direction applies inside the isolated value. Treat them as separate decisions even when one HTML element supplies both.

For the journal's manufacturer reference, use bdi dir="ltr" because its format is known. For a technician's display name supplied at runtime, bdi without an explicit direction uses automatic direction. Do not force every name to LTR merely because it came through an API.

Value contractSuitable boundaryLimitation to remember
Known LTR identifier<bdi dir="ltr">Does not validate the identifier
Unknown-direction display name<bdi> or <bdi dir="auto">Automatic direction follows content
Known English phraseExisting semantic element with dir="ltr" and lang="en"Language and direction remain separate
An entire unknown-language noteIts own block with dir="auto"A Latin opening can select LTR for mixed text

bdi does not inherit its direction in the same way as an ordinary span; its default behaves like auto. A span with explicit dir="ltr" is also an appropriate isolation boundary in modern HTML. MDN's bdi reference describes the equivalence. The defect is the plain, undirected span, not the spelling of the tag.

Do not add lang="en" to every manufacturer code. A Latin identifier is not necessarily an English phrase. Conversely, an actual English note can need both a language declaration and LTR direction. MDN's dir reference separates base direction from other document metadata.

Make the value component own its boundary#

If batch codes appear in activity messages, search results and confirmations, their component should carry the rendering contract. Save this as BatchCode.jsx:

jsx
export function BatchCode({ children }) {  return <bdi dir="ltr">{children}</bdi>;}

The component deliberately accepts only its text content. It does not expose an interface-locale prop, infer direction from the current page, or let an incidental styling prop override the identifier's contract. Its callers provide a batch-code string, not a preformatted HTML string.

For unknown-direction display names, use a different contract rather than weakening the batch-code component:

jsx
export function TechnicianName({ children }) {  return <bdi>{children}</bdi>;}

This small distinction prevents a misleading abstraction in which one universal component blindly forces every interpolated value to LTR. An Arabic technician name and a manufacturer reference are both dynamic values, but they do not share the same content contract.

Place the boundary where the value is rendered. A selector that returns a string cannot encode an HTML boundary. A React component returning a string cannot either. A function returning the actual bdi element can, provided later code preserves that element instead of flattening it back into text.

Keep wrapping behavior separate from direction. white-space: nowrap is not isolation, and an inline block that changes line breaking is not a substitute for deciding the token's direction. Test a long reference at the narrowest supported width before adding rules that prevent wrapping.

Keep the value's punctuation inside its boundary#

The hyphen in the batch reference belongs to the identifier. It must remain inside the same boundary as the digits and suffix. A component that isolates only the Latin suffix leaves the separator exposed to the paragraph's directional context and no longer represents the reference as one unit.

Sentence punctuation has different ownership. If a translated sentence puts parentheses around a reference, keep those parentheses in the catalog around the named value placeholder. If a complete English phrase arrives with its own final punctuation, include that punctuation inside the phrase's LTR boundary. Do not detach it and append it as an unrelated React child.

Avoid repairing punctuation with added spaces. A space changes the text but does not establish which characters form the identifier or phrase. Its apparent result can change when a translator moves the placeholder, adds a count nearby or uses a different sentence ending.

Review the reference and its surrounding punctuation together in the browser. Verify that the identifier retains its established group order and that sentence punctuation belongs to the intended phrase. Parenthesis glyph orientation and visual placement are not established by a string-equality assertion. For a punctuation-specific failure after the value boundary is fixed, use parentheses and brackets in RTL.

Preserve placeholders as React nodes in translations#

A translated string with a placeholder is still a string. Interpolating a batch code through t() does not automatically surround it with an element. Translating the words and isolating the value are separate responsibilities.

Do not solve this by concatenating translated sentence fragments around a component. That fixes the word order in application code, even though a translator may need to move the reference or change the grammar around it. Keep the complete message in the catalog and let its placeholder resolve to a React element.

In an application already configured with react-i18next, these resources belong in the default translation namespace:

json
{  "en": {    "translation": {      "batchTransferred": "Batch <batch>{{code}}</batch> was moved to the incubator."    }  },  "ar": {    "translation": {      "batchTransferred": "نُقلت الدفعة <batch>{{code}}</batch> إلى الحاضنة."    }  }}

The resource object follows i18next's language and namespace nesting. The batch tag is a named component placeholder. Render it using the BatchCode component from the preceding file:

jsx
import { Trans, useTranslation } from "react-i18next";import { BatchCode } from "./BatchCode.jsx"; export function TranslatedBatchTransfer({ batchCode }) {  const { t } = useTranslation();   return (    <p>      <Trans        t={t}        i18nKey="batchTransferred"        values={{ code: batchCode }}        components={{ batch: <BatchCode /> }}      />    </p>  );}

This component inherits the interface's paragraph direction from the surrounding document. Its code placeholder retains LTR isolation in either language. The hook supplies the active translation function and handles language changes; Trans alone does not subscribe to language changes or load the needed resources. The react-i18next documentation covers named component placeholders and that distinction.

That API can also allow translation attributes to override component props. Here, BatchCode fixes dir internally and ignores extra props. Keep the catalog contract limited to the named placeholder and its text interpolation; direction is a content invariant owned by the component.

Review every translated branch, including plural branches and fallback messages, for the same boundary. A translation that keeps {{code}} but removes <batch> has preserved the data placeholder while losing the display contract. Give translators context explaining what the tag protects.

Use rich message callbacks with React Intl too#

React Intl offers the same separation through rich-text message tags. Within an existing IntlProvider, the Arabic batchTransferred message can be نُقلت الدفعة <batch>{code}</batch> إلى الحاضنة.. Use the message syntax expected by that library; it differs from i18next interpolation syntax.

jsx
import { FormattedMessage } from "react-intl";import { BatchCode } from "./BatchCode.jsx"; export function IntlBatchTransfer({ batchCode }) {  return (    <p>      <FormattedMessage        id="batchTransferred"        defaultMessage="Batch <batch>{code}</batch> was moved to the incubator."        values={{          code: batchCode,          batch: (chunks) => <BatchCode>{chunks}</BatchCode>        }}      />    </p>  );}

The provider supplies the active catalog. The callback turns the named message tag into the isolating component, while the translator retains control of the sentence. React Intl's component documentation describes rich-text callbacks. Configuring its generic text wrapper as a fragment does not supply isolation by itself.

Keep extraction and review aware of the named tag. Testing only that a message ID exists will miss a translation that moves the code outside the boundary. The useful assertion concerns the rendered element and its contents, rather than the presence of braces in a catalog string.

Highlight inside the token, not around its pieces#

Search highlighting introduces a second component boundary that can undo the first. A highlighter may split a reference into matched and unmatched substrings and return an array of text and mark elements. Those pieces still represent one identifier.

Keep one batch-code boundary outside the highlight output. The following standalone example highlights a literal query and uses the shared component:

jsx
import { BatchCode } from "./BatchCode.jsx"; export function HighlightedBatchCode({ code, query }) {  const start = query ? code.indexOf(query) : -1;  if (start < 0) return <BatchCode>{code}</BatchCode>;   const end = start + query.length;  return (    <BatchCode>      {code.slice(0, start)}      <mark>{code.slice(start, end)}</mark>      {code.slice(end)}    </BatchCode>  );}

This is a case-sensitive literal search, not a general Arabic search algorithm. Its purpose is to preserve one directional boundary around the complete code. Do not separately auto-direct the digit group, the separator and the suffix: that discards the identifier's structure.

The same reasoning applies to an inline link. If the complete reference is the link, the link can carry dir="ltr"; otherwise keep the isolating value component inside it. Avoid leaving the suffix outside the boundary because a badge or formatting rule styles it separately. When reviewing a DOM snapshot, check what the boundary actually encloses.

Distinguish CSS isolation from alignment and overrides#

A correct bdi can still be affected by application CSS. Inspect the winning styles when the component appears correct in isolation but fails in a product page. Pay particular attention to rules that reset unicode-bidi or impose direction on every descendant.

text-align: right changes line alignment. It does not isolate a reference or establish the required internal order. Likewise, direction: ltr and unicode-bidi: isolate are different CSS properties. CSS Writing Modes specifies that separation and distinguishes isolation from a directional override.

If a legacy renderer only permits spans, a controlled class can express both properties:

css
.batch-code {  direction: ltr;  unicode-bidi: isolate;}

Apply it to the span containing exactly the reference. Prefer semantic HTML direction where the renderer permits it, and verify the class survives its styling pipeline. Do not apply unicode-bidi: bidi-override to the feed to force a screenshot into the desired order. An override suppresses normal directional resolution within its scope, which is a different operation from isolating one value.

Keep component layout out of this diagnosis. Reversing a flex row rearranges boxes; it does not repair the characters inside a paragraph. If the buttons are on the wrong side too, handle that as a separate layout defect. RTL versus bidi explains the distinction without turning every text bug into a page-mirroring task.

Check the rendered location during updates and hydration#

Reusing the same React component for a different record does not change its content contract. The boundary should remain present when a pending activity becomes a completed activity, a reference is replaced, or a compact notification reuses the message renderer.

Watch for a loading branch that returns a component and a completed branch that returns a flattened string. Also inspect memoized formatted messages whose dependencies omit the locale or updated reference. A stale message and a bidi error can look similar, but their stored and rendered values differ in different ways.

Server-rendered output needs the same locale, message and boundary on the initial client render. Do not wait for a mount effect to add isolation after displaying an unisolated server sentence. React's hydration documentation requires matching initial output and treats mismatches as bugs. Suppressing the warning does not supply a missing text boundary.

Portals add another distinction. A notification can retain its translation context while being placed outside the DOM subtree carrying dir="rtl". React's portal documentation explains how React ancestry and physical DOM placement differ. Inspect the actual notification element's inherited direction. The code's internal LTR boundary and the Arabic sentence's RTL boundary must both survive.

Keep markup, plain strings and editable values separate#

Writing "<bdi>" into a JavaScript string does not create a React element when that string is rendered normally. It becomes text. Do not switch to dangerouslySetInnerHTML merely to get a directional wrapper around interpolated data. That replaces a text-rendering task with HTML injection and requires a separate trust and sanitization policy. React's common DOM reference explains the raw-HTML API and its risks.

HTML isolation also does not travel automatically into a clipboard string, a downloadable text report, a title attribute or an aria-label. Those channels cannot contain a live bdi element. Define each output's needs instead of serializing the visible React node and assuming its semantics survive.

For the journal's copy-reference action, copy the source identifier by itself. The recipient receives the canonical code without depending on the surrounding Arabic sentence. If a plain-text message must mix directions, treat its directional formatting as a separate output concern; when not to use bidi controls explains why markup is preferable where available.

Do not store invisible controls inside the batch identifier as a universal UI fix. They can become part of equality checks, searches and exported values. Also do not strip controls from arbitrary user prose without a content policy: legitimate multilingual text can contain directional formatting.

An editable input has another contract again. Wrapping an input in bdi does not replace choosing direction on the control. Preserve its raw editing value and decide its direction from the accepted content. Avoid solving a display-only activity-message problem by rewriting the form's state.

Build a regression that can fail for the right reason#

Begin with the smallest complete Arabic sentence that fails, keeping the production value's shape. A reference displayed by itself is an inadequate reproduction: its surrounding text is part of the bug.

Use the journal's fixtures to cover distinct directional contracts:

FixtureWhat the test establishes
Digit-first batch code 294805-ORCHID after Arabic textThe original failing interpolation
Latin-first variant ORCHID-294805A passing-looking value must not mask the missing boundary
Technician name هالة مراد and an English nameUnknown-direction content is not forced to LTR
The same code in translated messages and highlighted resultsBoth pipelines retain the complete value boundary
An updated code and a message rendered through a portalDynamic branches and actual DOM ancestry are covered

Separate structural checks from visual verification. A component test can assert that a bdi with dir="ltr" contains the entire reference, including its hyphen and suffix. It can also confirm that translations and highlighted children retain the original text. Rendering to an HTML string is sufficient for those structural assertions. React's static rendering API produces markup, not a browser layout result.

For the visual test, render the fixture in a browser with production styles. Compare the digit-first reference against a standalone LTR reference, then remove its isolation boundary as a deliberate negative test. The broken case should show the original mismatch. If both cases look identical, inspect whether another wrapper, an inline-block rule or a different fixture has already changed the context.

In DevTools, inspect the paragraph's direction, the value's direction, the unicode-bidi value and the precise contents of the isolating element. MDN documents getComputedStyle for inspecting resolved styles. A screenshot shows the glyph order; a textContent assertion or copy test shows logical order. Use both forms of evidence for their respective questions.

Capture the Arabic message at a width that also exercises wrapping, then revisit it after changing languages and updating the reference. Verify the English message too. A repair that manually swaps the stored code may conceal one Arabic screenshot while corrupting the English output.

A free Ritla scan can report unisolated bidi hazards: phones, emails, Latin tokens inside Arabic text R021. For a React interpolation that still fails, continue with how browsers render mixed-direction text; for a wrapper decision, compare bdi with dir="auto".

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