react-spectrum icon indicating copy to clipboard operation
react-spectrum copied to clipboard

useLocalizedStringFormatter not working with variables

Open ritz078 opened this issue 1 year ago • 3 comments

Provide a general summary of the issue here

Variables are not being replaced in translated strings

🤔 Expected Behavior?

export const messages = {
  en: { greeting: "Hello, {name} !" },
  "en-Gb": { greeting: "Hello, {name} !" },
  es: { greeting: "Hola, {name} !" },
  fi: { greeting: "Hei, {name} !" },
  fr: { greeting: "Bonjour, {name} !" },
  "fr-CA": { greeting: "Bonjour {name} !" },
  de: { greeting: "Hallo, {name} !" },
  it: { greeting: "Ciao, {name} !" },
  cs: { greeting: "Ahoj, {name} !" },
  cy: { greeting: "Helo, {name} !" },
  da: { greeting: "Hej, {name} !" },
  el: { greeting: "Γεια σου, {name} !" },
  he: { greeting: "שלום, {name} !" },
  hr: { greeting: "Bok, {name} !" },
  id: { greeting: "Halo, {name} !" },
  ja: { greeting: "こんにちは、{name} さん!" },
  ko: { greeting: "안녕하세요, {name} !" },
  ms: { greeting: "Hai, {name} !" },
  nl: { greeting: "Hallo, {name} !" },
  nb: { greeting: "Hei, {name} !" },
  pl: { greeting: "Cześć, {name} !" },
  pt: { greeting: "Olá, {name} !" },
  "pt-PT": { greeting: "Olá, {name} !" },
  ru: { greeting: "Привет, {name} !" },
  sk: { greeting: "Ahoj, {name} !" },
  sl: { greeting: "Zdravo, {name} !" },
  sv: { greeting: "Hej, {name} !" },
  th: { greeting: "สวัสดี, {name} !" },
  tr: { greeting: "Merhaba, {name} !" },
  uk: { greeting: "Привіт, {name} !" },
  "zn-Hans": { greeting: "你好,{name} !" },
  "zn-Hant": { greeting: "你好,{name} !" },
};

const stringFormatter = useLocalizedStringFormatter(messages);

stringFormatter.format("greeting", { name: "John" }) // "Hello John !"

😯 Current Behavior

The above code prints Hello {name} !

🖥️ Steps to Reproduce

https://codesandbox.io/p/sandbox/bitter-resonance-3783tv?file=%2Fsrc%2FApp.js%3A56%2C24-56%2C30

Version

3.32.1

What browsers are you seeing the problem on?

Chrome

What operating system are you using?

MacOS

🧢 Your Company/Team

PSPDFKit

ritz078 avatar Apr 06 '24 16:04 ritz078

The strings need to be compiled with @internationalized/string-compiler at build time before they are passed into the formatter. Sorry there's not much documentation on these packages at the moment.

devongovett avatar Apr 07 '24 01:04 devongovett

But does that mean that you cannot change these translations at runtime ? We are using this in an SDK where we allow overriding existing translations which works well in case of useMessageFormatter but not by useLocalizedStringFormatter.

ritz078 avatar Apr 07 '24 21:04 ritz078

Yes, these would need to be compiled. We moved from useMessageFormatter to useLocalizedStringFormatter in order to avoid including the compiler at runtime to reduce bundle size.

devongovett avatar Apr 08 '24 17:04 devongovett