Skip to content

Arabic localization in React

Learn how to load Arabic messages in React, handle plural forms, format dates and numbers, and translate attributes without hiding missing copy.

By , Founder of Ritla

Guide12 min read

An Arabic React screen can have a translated heading and still say “2 cards” in its summary, announce an English clear button, or render an English message when an Arabic key is missing. Loading an Arabic catalogue establishes only that some messages are available.

The application also needs the correct plural branch, explicit formatting choices, translated attributes, and a defined relationship between the selected locale and document direction. These concerns meet in the component that renders a message, but they require different checks.

This guide uses a fictional flashcard app for baking vocabulary. It shows a working message structure with react-i18next, explains the corresponding React Intl approach, and identifies the failures that can remain behind an apparently translated interface.

Choose a message system and keep its syntax consistent#

React-i18next and React Intl both support Arabic localization, but their message formats and runtime contracts differ. Use the system that fits the application's existing extraction, translation, and delivery workflow. Adding a second system solely for Arabic creates another set of catalogues and loading rules to maintain.

Concernreact-i18nextReact Intl
Message lookupTranslation keys within namespacesMessage descriptors and IDs
Arabic pluralsCategory-suffixed keys in the current JSON formatICU plural branches inside a message
React accessuseTranslationuseIntl or formatted components
Rich textTrans with controlled React componentsRich-text values in formatted messages
Initialization boundaryAn initialized i18next instanceAn IntlProvider configuration

The examples below use i18next's current JSON v4 suffix convention. Its JSON format documentation distinguishes that convention from older numeric plural suffixes. Do not mix examples from different catalogue formats and expect the same key lookup.

Neither message system establishes the HTML document's direction simply by translating a string. Keep message configuration and document configuration coordinated, while allowing each layer to perform its own job.

Load a complete initial namespace before rendering it#

For the flashcard review screen, place its initial messages in a review namespace. This Arabic JSON object is the resource called arReview in the initialization example:

json
{  "heading": "مراجعة مصطلحات الخَبز",  "start": "بدء المراجعة",  "searchLabel": "البحث في البطاقات",  "searchPlaceholder": "اكتب كلمة أو موضوعًا",  "clearSearch": "مسح البحث",  "due_zero": "لا توجد بطاقات للمراجعة.",  "due_one": "توجد بطاقة واحدة للمراجعة.",  "due_two": "توجد بطاقتان للمراجعة.",  "due_few": "توجد {{countText}} بطاقات للمراجعة.",  "due_many": "توجد {{countText}} بطاقة للمراجعة.",  "due_other": "توجد {{countText}} بطاقة للمراجعة.",  "deckMessage": "أنت تراجع مجموعة <deck>{{name}}</deck>."}

The corresponding English resource, called enReview, has the same message purposes but English plural branches:

json
{  "heading": "Review baking vocabulary",  "start": "Start review",  "searchLabel": "Search cards",  "searchPlaceholder": "Enter a word or topic",  "clearSearch": "Clear search",  "due_one": "There is one card to review.",  "due_other": "There are {{countText}} cards to review.",  "deckMessage": "You are reviewing <deck>{{name}}</deck>."}

Use complete messages rather than translating a count, noun, and suffix separately. The Arabic one and two forms do not need to print a numeral in this wording. That is a message decision, not a missing interpolation.

This initializer assumes i18next and react-i18next are installed. The caller loads the two JSON objects and passes the resources structure shown in its comment.

js
import { createInstance } from 'i18next';import { initReactI18next } from 'react-i18next'; export async function createReviewI18n(locale, resources) {  if (!['ar', 'en'].includes(locale)) {    throw new Error('Unsupported review locale');  }  const instance = createInstance();  await instance.use(initReactI18next).init({    lng: locale,    supportedLngs: ['ar', 'en'],    fallbackLng: 'en',    ns: ['review'],    defaultNS: 'review',    resources,    interpolation: { escapeValue: false }  });  return instance;} // resources: { ar: { review: arReview }, en: { review: enReview } }

Initialization is asynchronous; await it before rendering this screen with that instance. The i18next configuration reference describes languages, resources, namespaces, and fallback settings.

The example disables i18next interpolation escaping because its results are rendered as React text or through controlled React components. React handles text escaping at that boundary. Do not reuse that assumption for raw HTML output or dangerouslySetInnerHTML; i18next's interpolation documentation explains its escaping option.

Connect the instance and direction to the same locale#

Pass the initialized instance through I18nextProvider. This local boundary assumes locale is the same validated choice used by createReviewI18n:

jsx
import { I18nextProvider } from 'react-i18next'; export function ReviewBoundary({ instance, locale, children }) {  if (!['ar', 'en'].includes(locale)) {    throw new Error('Unsupported review locale');  }  return (    <I18nextProvider i18n={instance}>      <section lang={locale} dir={locale === 'ar' ? 'rtl' : 'ltr'}>        {children}      </section>    </I18nextProvider>  );}

The provider supplies the instance through React context; the section supplies HTML semantics. A full-page application should set the document's lang and dir from that same resolved choice in its root layout. This local section alone does not change an otherwise LTR document.

Keep the selected interface locale explicit. A missing Arabic message that falls back to English does not mean the whole interface should switch to LTR. Conversely, resolving an unsupported route to an English interface should update the actual interface configuration, rather than leaving contradictory root attributes.

For regional variants, define the supported mapping deliberately. The example supports only ar and en; a production application may choose regional formatting while sharing base Arabic messages. Do not silently accept arbitrary language tags and assume every one has the same translation coverage or market conventions. See HTML direction for the document boundary.

Pass a numeric count and exercise all Arabic categories#

A singular-versus-plural conditional cannot choose all Arabic forms. The current i18next convention uses _zero, _one, _two, _few, _many, and _other for Arabic, with the numeric count option selecting the form.

Keep the selection input numeric. A formatted string belongs in the message's displayed value, not in the plural selector. This component demonstrates the separation:

jsx
import { useTranslation } from 'react-i18next'; export function DueSummary({ count }) {  const { t, i18n } = useTranslation('review');  if (!Number.isInteger(count) || count < 0) {    throw new Error('Review count must be a nonnegative integer');  }  const locale = i18n.resolvedLanguage || 'en';  const countText = new Intl.NumberFormat(locale, {    numberingSystem: locale === 'ar' ? 'arab' : 'latn'  }).format(count);  return <p>{t('due', { count, countText })}</p>;}

The resource keys and component perform the same job in both languages: report how many cards are due. The formatter explicitly selects Arabic-Indic digits for this product's Arabic interface. A product using Western digits can choose latn instead.

The i18next plural documentation requires the option name count; naming it total does not invoke that plural contract. Its zero override is also worth understanding when reviewing messages that choose special wording for no items.

Use counts 0, 1, 2, 3, 11, and 100 to reach Arabic's six categories. Then include boundary values that share a category but produce different displayed numbers. Have the Arabic sentences reviewed in context: a plural engine selects a branch, but it cannot establish that the translator chose the right noun form for that sentence.

Do not copy English key parity rules blindly. English needs fewer plural suffixes here. Validate message purposes across languages and category completeness within each language, rather than requiring identical literal key lists.

Use ICU branches when the app already uses React Intl#

For React Intl, represent the same Arabic summary as one ICU message with plural branches. The values still include a numeric count for selection. FormatJS's ICU syntax guide explains category branches and exact-value selectors.

This is the ICU message pattern to store under review.due in the Arabic React Intl catalogue. It preserves the separate numeric selector and formatted display value used in the i18next example:

text
{count, plural,  zero {لا توجد بطاقات للمراجعة.}  one {توجد بطاقة واحدة للمراجعة.}  two {توجد بطاقتان للمراجعة.}  few {توجد {countText} بطاقات للمراجعة.}  many {توجد {countText} بطاقة للمراجعة.}  other {توجد {countText} بطاقة للمراجعة.}}

Within the configured provider, the corresponding component receives those two values from its caller:

jsx
import { FormattedMessage } from 'react-intl'; export function IntlDueSummary({ count, countText }) {  return (    <p>      <FormattedMessage id="review.due" values={{ count, countText }} />    </p>  );}

Do not treat one as a synonym for the literal number one in every language or every message system. ICU exact selectors such as =0 have a separate meaning from category names. Likewise, other is a required general branch, not a translation you can leave in English because it sounds like an unlikely edge case.

Render messages through the application's IntlProvider with the selected locale and message catalogue. React Intl's formatted components provide message and value rendering. Use its string-formatting API for string-valued attributes rather than placing a React element in an aria-label or placeholder prop.

Keep the resource format consistent with the runtime. I18next's {{countText}} interpolation and suffix keys are not directly interchangeable with ICU message syntax. A migration needs converted catalogues, placeholder validation, and plural tests; replacing the React hook alone does not convert the messages.

If translators already work with ICU, retain that workflow and document rich-text placeholders and formatting conventions. If they work with namespaced i18next resources, retain those contracts. Both approaches still need Arabic review, HTML direction, and tests for missing messages.

Translate the text hidden in attributes#

Buttons without visible text, search placeholders, tooltips, alternative text, and validation messages belong in the catalogue. They are easy to miss in a heading-only review because some appear only during interaction or assistive-technology use.

This controlled search component uses the earlier namespace. Its caller supplies the current value and the change/clear handlers:

jsx
import { useTranslation } from 'react-i18next'; export function ReviewSearch({ value, onChange, onClear }) {  const { t } = useTranslation('review');  return (    <div>      <label>        <span>{t('searchLabel')}</span>        <input type="search" value={value} onChange={onChange}          placeholder={t('searchPlaceholder')} />      </label>      <button type="button" onClick={onClear}        aria-label={t('clearSearch')} title={t('clearSearch')}>        <span aria-hidden="true">×</span>      </button>    </div>  );}

The clear action has an Arabic accessible name and tooltip. The search field has a persistent label; the placeholder supplements it. Its base direction inherits from the review boundary, which is appropriate for this example's Arabic search interface.

Test the names that actually render, including wrappers that supply their own English defaults. An icon component's internal title or a library's generated close label can remain untranslated even when the surrounding JSX uses t.

Custom validation copy needs its own keys. Document language does not establish the language of every browser-generated message. When browser validation wording matters, test the supported browser and UI-language combinations; do not assume changing lang translates the browser's interface.

Keep rich interpolation inside a translated sentence#

A deck name can contain Arabic, English, or punctuation. The translation should own where that name appears, while the component supplies a direction boundary around it.

The earlier deckMessage contains a named <deck> placeholder. This component maps that placeholder to controlled React markup:

jsx
import { Trans, useTranslation } from 'react-i18next'; export function DeckMessage({ name }) {  const { t } = useTranslation('review');  return (    <p>      <Trans t={t} i18nKey="deckMessage" values={{ name }}        components={{ deck: <bdi /> }} />    </p>  );}

The Trans documentation describes named components and interpolation. useTranslation supplies the translation function and subscribes this component to language changes; Trans alone is not a replacement for loading resources or subscribing to the selected language.

For an independent user-supplied name, <bdi> can determine its direction from its own contents. A fixed-format identifier may need an explicitly LTR boundary instead. Keep language tagging separate when the inserted text has a known foreign language. See bidi isolation for those distinctions.

Do not break the sentence into independently translated fragments to place the React element between them. That fixes English word order into the component and limits Arabic translation choices. Keep the placeholder name and interpolation values stable, and validate that each translated message retains the required placeholders.

Treat the catalogue as controlled message content. A rich-text placeholder is a mapping to approved components, not permission for arbitrary user input to become markup or navigation attributes.

Give translators enough context to choose the sentence#

A short English label can hide several meanings. In the flashcard app, “Review” could name the activity, start a session, or ask someone to inspect a shared deck. Give those purposes separate keys and descriptions even if the English strings happen to match.

Document whether a count refers to due cards, completed cards, or the size of the whole deck. Reusing the due-card message after a filter changes the visible count can produce grammatically correct Arabic that describes the wrong quantity. The message's meaning belongs in its contract alongside its placeholders.

If a message addresses a person, decide whether its wording needs grammatical variants. Do not derive a person's grammatical gender from their display name. Use an explicitly supported preference or translator-approved wording that avoids needing that inference. Keep any relevant variants within complete messages, so Arabic word order remains available to the translator.

Provide screenshots or component previews showing where messages appear, including available width and associated actions. A translator reviewing only a JSON value cannot establish whether a phrase names a button, explains an error, or labels a field. Review the selected wording in that actual role.

Specify number and date policy beyond the message locale#

Choosing Arabic messages does not decide the product's digits, calendar, or timezone. Make those choices explicit at the formatting boundary. This formatter factory supports the same two interface locales as the example:

js
export function reviewFormatters(locale) {  if (!['ar', 'en'].includes(locale)) {    throw new Error('Unsupported review locale');  }  const numberingSystem = locale === 'ar' ? 'arab' : 'latn';  return {    count: new Intl.NumberFormat(locale, { numberingSystem }),    dueAt: new Intl.DateTimeFormat(locale, {      numberingSystem,      calendar: 'gregory',      timeZone: 'Asia/Amman',      dateStyle: 'medium',      timeStyle: 'short'    })  };}

The timezone is this fictional app's chosen review schedule zone, not a default for every Arabic user. A real product may use an account preference or another scheduling rule. MDN's number formatting and date formatting references describe these options.

Keep timestamps and numbers as data until display. Do not submit a localized date string as the scheduling identifier or sort counts lexicographically after formatting them. A date-only review day also needs a different data contract from a timestamp representing an instant.

If a formatter is memoized, include the current locale and relevant preferences in its dependencies. A formatter created once can keep English output after the labels switch to Arabic. Check the page summary, tooltip, notification, and exported view for the same convention rather than approving one formatted number.

Make missing translations visible during development#

The initializer uses English fallback so a missing Arabic message can remain readable. That is a recovery policy, not evidence of Arabic coverage. I18next's fallback documentation describes how language variants, keys, and namespaces participate in resolution.

Test Arabic resources directly as well as rendering the UI. A test that merely asserts the result is nonempty can pass with an English fallback or a raw key. A catalogue check should establish that each required Arabic message and plural branch exists in the Arabic resource itself.

Check placeholder structure too. An Arabic string can exist while dropping the deck name or referring to a placeholder the caller never supplies. Validate rich tags, interpolation names, and plural branches with the selected message tooling. Then review the rendered sentences, because structural validity does not prove their grammar.

Separate missing content from intentional foreign content. A deck's English title may be legitimate; an English clear-search action on the Arabic route is a different condition. A blanket test banning Latin characters would reject useful names without reliably identifying untranslated interface text.

Include recoverable failures, empty results, loading copy, and notifications in coverage. Their keys can remain unused in a normal populated-screen test. Record which namespace owns each message so a missing key is not accidentally satisfied by an unrelated shared catalogue.

Static extraction also needs explicit coverage for dynamically chosen keys. A call that constructs a key from an arbitrary server status can evade an extractor's literal-key inventory. Map supported status codes to declared message IDs, retain those IDs in the extraction workflow, and define an unknown-status message. Keep the raw server status available for diagnostics rather than using it as interface copy.

Review stale keys separately from missing ones. A catalogue containing an Arabic message that no component requests does not establish coverage for a renamed key. Tie validation to the identifiers actually used by the application and its supported dynamic mappings.

Keep server rendering and language switching consistent#

On the server, use request-scoped language state. Do not call changeLanguage on one mutable global instance for concurrent Arabic and English requests. React-i18next's SSR guidance covers per-request instances and passing initial translations to the client.

Hydrate with the same initial locale and namespaces that produced the HTML. Otherwise labels, plural branches, and formatted values can differ before any user interaction. Include the document attributes and formatting policy in that agreement, not just the visible message bundle.

For lazy namespaces, show a defined loading state. useTranslation can use Suspense while resources are pending; disabling that behavior means the application must handle readiness itself. Do not mistake an unloaded namespace for a missing Arabic translation and permanently cache an English fallback.

During a language switch, coordinate resource loading, the selected interface locale, document direction, and library configuration. Preserve drafts and current deck identity when those should survive. Test switching with a search entered and a review session open, then confirm that delayed responses and callbacks do not restore old-language messages.

If the API returns localized deck descriptions or instructions, include the requested language in the data-loading contract and cache identity. Reusing an English response after the interface switches to Arabic can leave stale content even when every React message key is translated. Keep user-authored content distinct from server-localized interface content: changing the interface language does not translate a learner's notes.

Test rapid switches with delayed responses. The final screen should correspond to the final selected locale, and an older response should not replace its localized data. A resource-loading test and an API-response race test cover different failures.

Verify message selection and the rendered interface separately#

Begin with catalogue checks for required purposes, Arabic plural categories, and placeholder compatibility. Exercise the numeric plural fixtures through the real message runtime, with the configured fallback policy accounted for. Verify the expected Arabic branch instead of checking only that a string was returned.

Render the review screen in both languages with the same data. Check visible actions, placeholders, accessible names, tooltips, and rich deck names. Include a missing-key fixture so reviewers can see how fallback appears and distinguish it from an intentionally English content value.

Then review the actual Arabic layout at the panel widths the product uses. Long translations can wrap differently, and isolated values need visual inspection in their sentence. Correct message selection does not establish that the browser displays the whole sentence without clipping.

Finally, cold-load the Arabic route, delay a namespace, and switch languages without reloading. Confirm that direction, labels, count formatting, and scheduled dates agree throughout the resulting states. Use an Arabic-language review for wording and grammar alongside the engineering checks.

A free Ritla scan can report Untranslated attribute text (placeholder, alt, title, aria-label, button value) R012 and Arabic-Indic and Western digits mixed in the same context R061 in the rendered interface. For the next localization issue, see Arabic localization testing and why translation QA is not enough.

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