Search code examples
javascriptreactjsi18nextreact-i18next

React i18n, how to interpolate to a string (i.e. without using <Trans> component)?


I have this function in my React component:

const fireError = (n) => {
   alert(`The value should go over ${n}% to be accepted.`);
}

in my translation JSON I have this:

{ "percentage": "The value should go over {{percentage}} to be accepted" }

How can I make this work? Of course I cannot use the Trans component.


Solution

  • You can use the i18n service directly:

    // import it
    import i18n from "i18next";
    
    // in your React component
    const fireError = (n) => {
       alert(i18n.t('percentage', { percentage: n }));
    }
    

    Keep in mind that the library has to be initialized before calling this function - i18n.init() must have already been invoked.