Translation Escaping

Documentation

  • Overview
  • Translation Escaping

Translation Apostrophe Escaping

Problem

React's linter (ESLint) warns about unescaped apostrophes (') in JSX content with the error:

Error: `'` can be escaped with `'`, `‘`, `'`, `’`. react/no-unescaped-entities

This occurs when translation strings contain apostrophes, which is common in many languages.

Solution

We've implemented an automatic apostrophe escaping mechanism in our i18n setup that works in two ways:

1. Global Escaping in i18n Configuration

The i18n.js file has been modified to automatically escape all apostrophes in translation strings using a custom formatter in the interpolation configuration:

javascript
interpolation: {    escapeValue: false, // React already does escaping    format: function(value, format, lng, options) {        // Always apply apostrophe escaping to string values        if (typeof value === 'string') {            return escapeApostrophes(value)        }        return value    }}

This ensures that all translations retrieved through the standard t() function will have apostrophes properly escaped.

2. Safe Translation Components and Hooks

For cases where you need more control, we've also created:

useSafeTranslation Hook

tsx
import { useSafeTranslation } from '@/components/utility/safe-translation';
function MyComponent() {  const { t } = useSafeTranslation();    return <div>{t('my.translation.key')}</div>;}

SafeTranslation Component

tsx
import { SafeTranslation } from '@/components/utility/safe-translation';
function MyComponent() {  return (    <div>      <SafeTranslation i18nKey="my.translation.key" />    </div>  );}

Implementation Details

  1. The escapeApostrophes utility function in lib/utils.ts handles the actual escaping
  2. The i18n configuration in i18n.js applies this escaping globally
  3. The SafeTranslation component and useSafeTranslation hook provide alternative ways to use escaped translations

Benefits

  • No more React linter warnings about unescaped entities
  • No need to manually escape apostrophes in translation files
  • Works automatically for all languages and components

Notes

  • This solution only escapes apostrophes ('). If you have other characters causing similar issues, you may need to extend the escaping function.
  • The escaping is done at runtime, so there's no need to modify the translation files themselves.