Skip to content

Escaped string in JSX is not unescaped in defaultValueΒ #664

@yoo2001818

Description

@yoo2001818

πŸ› Bug Report

In JSX, you can specify HTML entities (<, ", ", etc) in JsxText.

<Trans>
  &quot;Hello &amp; world!&#34;
</Trans>
// Would be parsed as... "Hello & world!"

These HTML entities are unescaped while compile time - so it would end up like this in the compiled code:

React.createElement(Trans, null, "\"Hello & world!\"");

However, i18next-parser's JsxLexer doesn't unescape JsxText properly, making defaultValue to be &quot;Hello &amp; world!&#34; in the example. Similiar to #663, if i18nKey is specified in other ways, it can be patched by specifying shouldUnescape to true.

But, if i18nKey is not specified (or shouldUnescape is not applied), react-i18next never sees the escaped string because it would only reside in the raw source code - the transpiler effectively removes the escape from the transpiled code, making the translation key to differ between the generated file and the actual code.

This can be resolved by changing JsxLexer's JsxText rendering routine - https://github.com/i18next/i18next-parser/blob/master/src/lexers/jsx-lexer.js#L186-L191

        if (child.kind === ts.SyntaxKind.JsxText) {
          return {
            type: 'text',
            content: unescape(child.text)
              .replace(/(^(\n|\r)\s*)|((\n|\r)\s*$)/g, '')
              .replace(/(\n|\r)\s*/g, ' '),
          };

Simply unescaping the text would resolve the problem. However, I'm not sure if I should send PR with a new dependency (e.g. unescape), or bundle simple unescape function inside (https://github.com/i18next/react-i18next/blob/master/src/unescape.js). I'll be looking forward for your suggestions!

To Reproduce

<Trans>
  &quot;Hello &amp; world!&#34;
</Trans>

is parsed/generated as-is - &quot;Hello &amp; world!&#34; is the defaultValue / i18nKey.

Expected behavior

"Hello & world!" should be the generated defaultValue / i18nKey.

Your Environment

  • runtime version: Node 14
  • i18next version: 11.18.6
  • os: Linux
  • any other relevant information

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions