1

I have built a form app using React. I'm using useState and useEffect which I think is pretty awesome. For brevity I include this toned down example below of what I'm trying to achieve.

   import DATA from './data.json'

   const [language, setLanguage] = useState('english');
   const [firstName, setFirstName] = useState('Bob');

   function App() {

       const getTranslation = (reference) => {
           let dictionary = DATA[language]
           return dictionary[reference]
       }

       return (
           <React.Fragment>
               <h1>{getTranslation('HowCanWeHelp')}</h1>
           </React.Fragment>
       );

   }

I am attempting to build my own simple language translation mechanism that pulls the strings from a JSON file.

The data returned from DATA['english'][HowCanWeHelp] is {firstName}, How can we help you?.

What is returned

{firstName}, How can we help you?

What is expected

Bob, How can we help you?

I'm not certain if this is even possible, but can I re-render JSX inside JSX? I've tried wrapping with React.Fragment tags, using dangerouslySetInnerHTML and trying my luck with React.createElement. A point in the right direction would be greatly appreciated.

I have read the following stackoverflow questions but the answers make little sense to me.

Return and Render JSX How to render (print) JSX as String? Render string as JSX in React.js

Agney
  • 18,522
  • 7
  • 57
  • 75
anastymous
  • 448
  • 5
  • 15

2 Answers2

1

Use string's replace method:

const getTranslation = (reference) => {
  let dictionary = DATA[language]
  return dictionary[reference].replace('{firstName}', firstName);
}

Here's a Working Sample Demo for your ref.

SiddAjmera
  • 38,129
  • 5
  • 72
  • 110
1

Most of the internationalisation libraries come with this feature by default. For eg. a popular internationalisation library for React, i18next can implement it with:

i18next.t('HowCanWeHelp', { firstName: "name" });

Docs on i18next interpolation

If you don't want a complete internationlisation solution and prefer your own dictionary solution, you can go with a microtemplating library like pupa

import pupa from "pupa";

return (
  <React.Fragment>
     <h1>{
       pupa(getTranslation('HowCanWeHelp'), {
         firstName: "name"
       })
     }</h1>
  </React.Fragment>
);
Agney
  • 18,522
  • 7
  • 57
  • 75