diff --git a/CHANGELOG.md b/CHANGELOG.md index dc16e35c..c4d711a0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,7 @@ +### 12.3.0 + +- optional lng prop for useTranslation (helping on server side [1637](https://github.com/i18next/react-i18next/issues/1637)) + ### 12.2.2 - try to fix conditional exports in package.json diff --git a/index.d.ts b/index.d.ts index 609901b6..f354e555 100644 --- a/index.d.ts +++ b/index.d.ts @@ -58,6 +58,7 @@ export interface UseTranslationOptions { keyPrefix?: TKPrefix; bindI18n?: string | false; nsMode?: 'fallback' | 'default'; + lng?: string; // other of these options might also work: https://github.com/i18next/i18next/blob/master/index.d.ts#L127 } diff --git a/react-i18next.js b/react-i18next.js index ecf5af82..66db0e8d 100644 --- a/react-i18next.js +++ b/react-i18next.js @@ -874,7 +874,7 @@ }); function getT() { - return i18n.getFixedT(null, i18nOptions.nsMode === 'fallback' ? namespaces : namespaces[0], keyPrefix); + return i18n.getFixedT(props.lng || null, i18nOptions.nsMode === 'fallback' ? namespaces : namespaces[0], keyPrefix); } var _useState = react.useState(getT), diff --git a/react-i18next.min.js b/react-i18next.min.js index 04f8c36c..3059e334 100644 --- a/react-i18next.min.js +++ b/react-i18next.min.js @@ -1 +1 @@ -!function(e,n){"object"==typeof exports&&"undefined"!=typeof module?n(exports,require("react")):"function"==typeof define&&define.amd?define(["exports","react"],n):n((e=e||self).ReactI18next={},e.React)}(this,(function(e,n){"use strict";function t(e,n){var t=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);n&&(r=r.filter((function(n){return Object.getOwnPropertyDescriptor(e,n).enumerable}))),t.push.apply(t,r)}return t}function r(e){for(var n=1;n=0||(a[t]=e[t]);return a}(e,n);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(r=0;r=0||Object.prototype.propertyIsEnumerable.call(e,t)&&(a[t]=e[t])}return a}function c(e,n){return function(e){if(Array.isArray(e))return e}(e)||function(e,n){var t=e&&("undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"]);if(null==t)return;var r,a,i=[],o=!0,s=!1;try{for(t=t.call(e);!(o=(r=t.next()).done)&&(i.push(r.value),!n||i.length!==n);o=!0);}catch(e){s=!0,a=e}finally{try{o||null==t.return||t.return()}finally{if(s)throw a}}return i}(e,n)||function(e,n){if(!e)return;if("string"==typeof e)return u(e,n);var t=Object.prototype.toString.call(e).slice(8,-1);"Object"===t&&e.constructor&&(t=e.constructor.name);if("Map"===t||"Set"===t)return Array.from(e);if("Arguments"===t||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t))return u(e,n)}(e,n)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function u(e,n){(null==n||n>e.length)&&(n=e.length);for(var t=0,r=new Array(n);t<]+?)[\s/>]|([^\s=]+)=\s?(".*?"|'.*?')/g;function p(e){var n={type:"tag",name:"",voidElement:!1,attrs:{},children:[]},t=e.match(/<\/?([^\s]+?)[/\s>]/);if(t&&(n.name=t[1],(l[t[1]]||"/"===e.charAt(e.length-2))&&(n.voidElement=!0),n.name.startsWith("!--"))){var r=e.indexOf("--\x3e");return{type:"comment",comment:-1!==r?e.slice(4,r):""}}for(var a=new RegExp(f),i=null;null!==(i=a.exec(e));)if(i[0].trim())if(i[1]){var o=i[1].trim(),s=[o,""];o.indexOf("=")>-1&&(s=o.split("=")),n.attrs[s[0]]=s[1],a.lastIndex--}else i[2]&&(n.attrs[i[2]]=i[3].trim().substring(1,i[3].length-1));return n}var d=/<[a-zA-Z0-9\-\!\/](?:"[^"]*"|'[^']*'|[^'">])*>/g,g=/^\s*$/,m=Object.create(null);var h=function(e,n){n||(n={}),n.components||(n.components=m);var t,r=[],a=[],i=-1,o=!1;if(0!==e.indexOf("<")){var s=e.indexOf("<");r.push({type:"text",content:-1===s?e:e.substring(0,s)})}return e.replace(d,(function(s,c){if(o){if(s!=="")return;o=!1}var u,l="/"!==s.charAt(1),f=s.startsWith("\x3c!--"),d=c+s.length,m=e.charAt(d);if(f){var h=p(s);return i<0?(r.push(h),r):((u=a[i]).children.push(h),r)}if(l&&(i++,"tag"===(t=p(s)).type&&n.components[t.name]&&(t.type="component",o=!0),t.voidElement||o||!m||"<"===m||t.children.push({type:"text",content:e.slice(d,e.indexOf("<",d))}),0===i&&r.push(t),(u=a[i-1])&&u.children.push(t),a[i]=t),(!l||t.voidElement)&&(i>-1&&(t.voidElement||t.name===s.slice(2,-1))&&(i--,t=-1===i?r:a[i]),!o&&"<"!==m&&m)){u=-1===i?r:a[i].children;var v=e.indexOf("<",d),y=e.slice(d,-1===v?void 0:v);g.test(y)&&(y=" "),(v>-1&&i+u.length>=0||" "!==y)&&u.push({type:"text",content:y})}})),r};function v(){if(console&&console.warn){for(var e,n=arguments.length,t=new Array(n),r=0;r2&&void 0!==arguments[2]?arguments[2]:{},r=n.languages[0],a=!!n.options&&n.options.fallbackLng,i=n.languages[n.languages.length-1];if("cimode"===r.toLowerCase())return!0;var o=function(e,t){var r=n.services.backendConnector.state["".concat(e,"|").concat(t)];return-1===r||2===r};return!(t.bindI18n&&t.bindI18n.indexOf("languageChanging")>-1&&n.services.backendConnector.backend&&n.isLanguageChangingTo&&!o(n.isLanguageChangingTo,e))&&(!!n.hasResourceBundle(r,e)||(!(n.services.backendConnector.backend&&(!n.options.resources||n.options.partialBundledLanguages))||!(!o(r,e)||a&&!o(i,e))))}function w(e,n){var t=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!n.languages||!n.languages.length)return b("i18n.languages were undefined or empty",n.languages),!0;var r=void 0!==n.options.ignoreJSONStructure;return r?n.hasLoadedNamespace(e,{precheck:function(n,r){if(t.bindI18n&&t.bindI18n.indexOf("languageChanging")>-1&&n.services.backendConnector.backend&&n.isLanguageChangingTo&&!r(n.isLanguageChangingTo,e))return!1}}):x(e,n,t)}function j(e){return e.displayName||e.name||("string"==typeof e&&e.length>0?e:"Unknown")}var S,E=/&(?:amp|#38|lt|#60|gt|#62|apos|#39|quot|#34|nbsp|#160|copy|#169|reg|#174|hellip|#8230|#x2F|#47);/g,N={"&":"&","&":"&","<":"<","<":"<",">":">",">":">","'":"'","'":"'",""":'"',""":'"'," ":" "," ":" ","©":"©","©":"©","®":"®","®":"®","…":"…","…":"…","/":"/","/":"/"},k=function(e){return N[e]},I={bindI18n:"languageChanged",bindI18nStore:"",transEmptyNodeValue:"",transSupportBasicHtmlNodes:!0,transWrapTextNodes:"",transKeepBasicHtmlNodesFor:["br","strong","i","p"],useSuspense:!0,unescape:function(e){return e.replace(E,k)}};function P(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};I=r(r({},I),e)}function R(){return I}function C(e){S=e}function T(){return S}var A=["format"],L=["children","count","parent","i18nKey","context","tOptions","values","defaults","components","ns","i18n","t","shouldUnescape"];function U(e,n){if(!e)return!1;var t=e.props?e.props.children:e.children;return n?t.length>0:!!t}function z(e){return e?e.props?e.props.children:e.children:[]}function B(e){return Array.isArray(e)?e:[e]}function K(e,t,i,o,s,c){if(""===t)return[];var u=o.transKeepBasicHtmlNodesFor||[],l=t&&new RegExp(u.join("|")).test(t);if(!e&&!l)return[t];var f={};!function e(t){B(t).forEach((function(t){"string"!=typeof t&&(U(t)?e(z(t)):"object"!==a(t)||n.isValidElement(t)||Object.assign(f,t))}))}(e);var p=h("<0>".concat(t,"")),d=r(r({},f),s);function g(e,t,r){var a=z(e),i=v(a,t.children,r);return function(e){return"[object Array]"===Object.prototype.toString.call(e)&&e.every((function(e){return n.isValidElement(e)}))}(a)&&0===i.length?a:i}function m(e,t,a,i,o){e.dummy&&(e.children=t),a.push(n.cloneElement(e,r(r({},e.props),{},{key:i}),o?void 0:t))}function v(t,s,f){var p=B(t);return B(s).reduce((function(t,s,h){var y,b,O,x=s.children&&s.children[0]&&s.children[0].content&&i.services.interpolator.interpolate(s.children[0].content,d,i.language);if("tag"===s.type){var w=p[parseInt(s.name,10)];!w&&1===f.length&&f[0][s.name]&&(w=f[0][s.name]),w||(w={});var j=0!==Object.keys(s.attrs).length?(y={props:s.attrs},(O=r({},b=w)).props=Object.assign(y.props,b.props),O):w,S=n.isValidElement(j),E=S&&U(s,!0)&&!s.voidElement,N=l&&"object"===a(j)&&j.dummy&&!S,k="object"===a(e)&&null!==e&&Object.hasOwnProperty.call(e,s.name);if("string"==typeof j){var I=i.services.interpolator.interpolate(j,d,i.language);t.push(I)}else if(U(j)||E){m(j,g(j,s,f),t,h)}else if(N){var P=v(p,s.children,f);t.push(n.cloneElement(j,r(r({},j.props),{},{key:h}),P))}else if(Number.isNaN(parseFloat(s.name))){if(k)m(j,g(j,s,f),t,h,s.voidElement);else if(o.transSupportBasicHtmlNodes&&u.indexOf(s.name)>-1)if(s.voidElement)t.push(n.createElement(s.name,{key:"".concat(s.name,"-").concat(h)}));else{var R=v(p,s.children,f);t.push(n.createElement(s.name,{key:"".concat(s.name,"-").concat(h)},R))}else if(s.voidElement)t.push("<".concat(s.name," />"));else{var C=v(p,s.children,f);t.push("<".concat(s.name,">").concat(C,""))}}else if("object"!==a(j)||S)1===s.children.length&&x?t.push(n.cloneElement(j,r(r({},j.props),{},{key:h}),x)):t.push(n.cloneElement(j,r(r({},j.props),{},{key:h})));else{var T=s.children[0]?x:null;T&&t.push(T)}}else if("text"===s.type){var A=o.transWrapTextNodes,L=c?o.unescape(i.services.interpolator.interpolate(s.content,d,i.language)):i.services.interpolator.interpolate(s.content,d,i.language);A?t.push(n.createElement(A,{key:"".concat(s.name,"-").concat(h)},L)):t.push(L)}return t}),[])}return z(v([{dummy:!0,children:e||[]}],p,B(e||[]))[0])}function V(e){var t=e.children,i=e.count,o=e.parent,c=e.i18nKey,u=e.context,l=e.tOptions,f=void 0===l?{}:l,p=e.values,d=e.defaults,g=e.components,m=e.ns,h=e.i18n,y=e.t,O=e.shouldUnescape,x=s(e,L),w=h||T();if(!w)return b("You will need to pass in an i18next instance by using i18nextReactModule"),t;var j=y||w.t.bind(w)||function(e){return e};u&&(f.context=u);var S=r(r({},R()),w.options&&w.options.react),E=m||j.ns||w.options&&w.options.defaultNS;E="string"==typeof E?[E]:E||["translation"];var N=d||function e(t,r){if(!t)return"";var i="",o=B(t),c=r.transSupportBasicHtmlNodes&&r.transKeepBasicHtmlNodesFor?r.transKeepBasicHtmlNodesFor:[];return o.forEach((function(t,o){if("string"==typeof t)i+="".concat(t);else if(n.isValidElement(t)){var u=Object.keys(t.props).length,l=c.indexOf(t.type)>-1,f=t.props.children;if(!f&&l&&0===u)i+="<".concat(t.type,"/>");else if(f||l&&0===u)if(t.props.i18nIsDynamicList)i+="<".concat(o,">");else if(l&&1===u&&"string"==typeof f)i+="<".concat(t.type,">").concat(f,"");else{var p=e(f,r);i+="<".concat(o,">").concat(p,"")}else i+="<".concat(o,">")}else if(null===t)v("Trans: the passed in value is invalid - seems you passed in a null child.");else if("object"===a(t)){var d=t.format,g=s(t,A),m=Object.keys(g);if(1===m.length){var h=d?"".concat(m[0],", ").concat(d):m[0];i+="{{".concat(h,"}}")}else v("react-i18next: the passed in object contained more than one variable - the object should look like {{ value, format }} where format is optional.",t)}else v("Trans: the passed in value is invalid - seems you passed in a variable like {number} - please pass in variables for interpolation as full objects like {{number}}.",t)})),i}(t,S)||S.transEmptyNodeValue||c,k=S.hashTransKey,I=c||(k?k(N):N),P=p?f.interpolation:{interpolation:r(r({},f.interpolation),{},{prefix:"#$?",suffix:"?$#"})},C=r(r(r(r({},f),{},{count:i},p),P),{},{defaultValue:N,ns:E}),U=K(g||t,I?j(I,C):N,w,S,C,O),z=void 0!==o?o:S.defaultTransParent;return z?n.createElement(z,x,U):U}var D={type:"3rdParty",init:function(e){P(e.options.react),C(e)}},F=n.createContext(),H=function(){function e(){!function(e,n){if(!(e instanceof n))throw new TypeError("Cannot call a class as a function")}(this,e),this.usedNamespaces={}}var n,t,r;return n=e,(t=[{key:"addUsedNamespaces",value:function(e){var n=this;e.forEach((function(e){n.usedNamespaces[e]||(n.usedNamespaces[e]=!0)}))}},{key:"getUsedNamespaces",value:function(){return Object.keys(this.usedNamespaces)}}])&&i(n.prototype,t),r&&i(n,r),e}();function W(e){return function(n){return new Promise((function(t){var a=M();e.getInitialProps?e.getInitialProps(n).then((function(e){t(r(r({},e),a))})):t(a)}))}}function M(){var e=T(),n=e.reportNamespaces?e.reportNamespaces.getUsedNamespaces():[],t={},r={};return e.languages.forEach((function(t){r[t]={},n.forEach((function(n){r[t][n]=e.getResourceBundle(t,n)||{}}))})),t.initialI18nStore=r,t.initialLanguage=e.language,t}var $=["children","count","parent","i18nKey","context","tOptions","values","defaults","components","ns","i18n","t","shouldUnescape"];var q=function(e,t){var r=n.useRef();return n.useEffect((function(){r.current=t?r.current:e}),[e,t]),r.current};function Y(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=t.i18n,o=n.useContext(F)||{},s=o.i18n,u=o.defaultNS,l=i||s||T();if(l&&!l.reportNamespaces&&(l.reportNamespaces=new H),!l){b("You will need to pass in an i18next instance by using initReactI18next");var f=function(e,n){return"string"==typeof n?n:n&&"object"===a(n)&&"string"==typeof n.defaultValue?n.defaultValue:Array.isArray(e)?e[e.length-1]:e},p=[f,{},!1];return p.t=f,p.i18n={},p.ready=!1,p}l.options.react&&void 0!==l.options.react.wait&&b("It seems you are still using the old wait option, you may migrate to the new useSuspense behaviour.");var d=r(r(r({},R()),l.options.react),t),g=d.useSuspense,m=d.keyPrefix,h=e||u||l.options&&l.options.defaultNS;h="string"==typeof h?[h]:h||["translation"],l.reportNamespaces.addUsedNamespaces&&l.reportNamespaces.addUsedNamespaces(h);var v=(l.isInitialized||l.initializedStoreOnce)&&h.every((function(e){return w(e,l,d)}));function y(){return l.getFixedT(null,"fallback"===d.nsMode?h:h[0],m)}var x=n.useState(y),j=c(x,2),S=j[0],E=j[1],N=h.join(),k=q(N),I=n.useRef(!0);n.useEffect((function(){var e=d.bindI18n,n=d.bindI18nStore;function t(){I.current&&E(y)}return I.current=!0,v||g||O(l,h,(function(){I.current&&E(y)})),v&&k&&k!==N&&I.current&&E(y),e&&l&&l.on(e,t),n&&l&&l.store.on(n,t),function(){I.current=!1,e&&l&&e.split(" ").forEach((function(e){return l.off(e,t)})),n&&l&&n.split(" ").forEach((function(e){return l.store.off(e,t)}))}}),[l,N]);var P=n.useRef(!0);n.useEffect((function(){I.current&&!P.current&&E(y),P.current=!1}),[l,m]);var C=[S,l,v];if(C.t=S,C.i18n=l,C.ready=v,v)return C;if(!v&&!g)return C;throw new Promise((function(e){O(l,h,(function(){e()}))}))}var _=["forwardedRef"];var J=["ns","children"];function Z(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},a=r.i18n,i=n.useContext(F)||{},o=i.i18n,s=a||o||T();s.options&&s.options.isClone||(e&&!s.initializedStoreOnce&&(s.services.resourceStore.data=e,s.options.ns=Object.values(e).reduce((function(e,n){return Object.keys(n).forEach((function(n){e.indexOf(n)<0&&e.push(n)})),e}),s.options.ns),s.initializedStoreOnce=!0,s.isInitialized=!0),t&&!s.initializedLanguageOnce&&(s.changeLanguage(t),s.initializedLanguageOnce=!0))}var G=["initialI18nStore","initialLanguage"];e.I18nContext=F,e.I18nextProvider=function(e){var t=e.i18n,r=e.defaultNS,a=e.children,i=n.useMemo((function(){return{i18n:t,defaultNS:r}}),[t,r]);return n.createElement(F.Provider,{value:i},a)},e.Trans=function(e){var t=e.children,a=e.count,i=e.parent,o=e.i18nKey,c=e.context,u=e.tOptions,l=void 0===u?{}:u,f=e.values,p=e.defaults,d=e.components,g=e.ns,m=e.i18n,h=e.t,v=e.shouldUnescape,y=s(e,$),b=n.useContext(F)||{},O=b.i18n,x=b.defaultNS,w=m||O||T(),j=h||w&&w.t.bind(w);return V(r({children:t,count:a,parent:i,i18nKey:o,context:c,tOptions:l,values:f,defaults:p,components:d,ns:g||j&&j.ns||x||w&&w.options&&w.options.defaultNS,i18n:w,t:h,shouldUnescape:v},y))},e.TransWithoutContext=V,e.Translation=function(e){var n=e.ns,t=e.children,r=c(Y(n,s(e,J)),3),a=r[0],i=r[1],o=r[2];return t(a,{i18n:i,lng:i.language},o)},e.composeInitialProps=W,e.date=function(){return""},e.getDefaults=R,e.getI18n=T,e.getInitialProps=M,e.initReactI18next=D,e.number=function(){return""},e.plural=function(){return""},e.select=function(){return""},e.selectOrdinal=function(){return""},e.setDefaults=P,e.setI18n=C,e.time=function(){return""},e.useSSR=Z,e.useTranslation=Y,e.withSSR=function(){return function(e){function t(t){var a=t.initialI18nStore,i=t.initialLanguage,o=s(t,G);return Z(a,i),n.createElement(e,r({},o))}return t.getInitialProps=W(e),t.displayName="withI18nextSSR(".concat(j(e),")"),t.WrappedComponent=e,t}},e.withTranslation=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function(a){function i(i){var o=i.forwardedRef,u=s(i,_),l=c(Y(e,r(r({},u),{},{keyPrefix:t.keyPrefix})),3),f=l[0],p=l[1],d=l[2],g=r(r({},u),{},{t:f,i18n:p,tReady:d});return t.withRef&&o?g.ref=o:!t.withRef&&o&&(g.forwardedRef=o),n.createElement(a,g)}i.displayName="withI18nextTranslation(".concat(j(a),")"),i.WrappedComponent=a;return t.withRef?n.forwardRef((function(e,t){return n.createElement(i,Object.assign({},e,{forwardedRef:t}))})):i}},Object.defineProperty(e,"__esModule",{value:!0})})); +!function(e,n){"object"==typeof exports&&"undefined"!=typeof module?n(exports,require("react")):"function"==typeof define&&define.amd?define(["exports","react"],n):n((e=e||self).ReactI18next={},e.React)}(this,(function(e,n){"use strict";function t(e,n){var t=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);n&&(r=r.filter((function(n){return Object.getOwnPropertyDescriptor(e,n).enumerable}))),t.push.apply(t,r)}return t}function r(e){for(var n=1;n=0||(a[t]=e[t]);return a}(e,n);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(r=0;r=0||Object.prototype.propertyIsEnumerable.call(e,t)&&(a[t]=e[t])}return a}function c(e,n){return function(e){if(Array.isArray(e))return e}(e)||function(e,n){var t=e&&("undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"]);if(null==t)return;var r,a,i=[],o=!0,s=!1;try{for(t=t.call(e);!(o=(r=t.next()).done)&&(i.push(r.value),!n||i.length!==n);o=!0);}catch(e){s=!0,a=e}finally{try{o||null==t.return||t.return()}finally{if(s)throw a}}return i}(e,n)||function(e,n){if(!e)return;if("string"==typeof e)return u(e,n);var t=Object.prototype.toString.call(e).slice(8,-1);"Object"===t&&e.constructor&&(t=e.constructor.name);if("Map"===t||"Set"===t)return Array.from(e);if("Arguments"===t||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t))return u(e,n)}(e,n)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function u(e,n){(null==n||n>e.length)&&(n=e.length);for(var t=0,r=new Array(n);t<]+?)[\s/>]|([^\s=]+)=\s?(".*?"|'.*?')/g;function p(e){var n={type:"tag",name:"",voidElement:!1,attrs:{},children:[]},t=e.match(/<\/?([^\s]+?)[/\s>]/);if(t&&(n.name=t[1],(l[t[1]]||"/"===e.charAt(e.length-2))&&(n.voidElement=!0),n.name.startsWith("!--"))){var r=e.indexOf("--\x3e");return{type:"comment",comment:-1!==r?e.slice(4,r):""}}for(var a=new RegExp(f),i=null;null!==(i=a.exec(e));)if(i[0].trim())if(i[1]){var o=i[1].trim(),s=[o,""];o.indexOf("=")>-1&&(s=o.split("=")),n.attrs[s[0]]=s[1],a.lastIndex--}else i[2]&&(n.attrs[i[2]]=i[3].trim().substring(1,i[3].length-1));return n}var d=/<[a-zA-Z0-9\-\!\/](?:"[^"]*"|'[^']*'|[^'">])*>/g,g=/^\s*$/,m=Object.create(null);var h=function(e,n){n||(n={}),n.components||(n.components=m);var t,r=[],a=[],i=-1,o=!1;if(0!==e.indexOf("<")){var s=e.indexOf("<");r.push({type:"text",content:-1===s?e:e.substring(0,s)})}return e.replace(d,(function(s,c){if(o){if(s!=="")return;o=!1}var u,l="/"!==s.charAt(1),f=s.startsWith("\x3c!--"),d=c+s.length,m=e.charAt(d);if(f){var h=p(s);return i<0?(r.push(h),r):((u=a[i]).children.push(h),r)}if(l&&(i++,"tag"===(t=p(s)).type&&n.components[t.name]&&(t.type="component",o=!0),t.voidElement||o||!m||"<"===m||t.children.push({type:"text",content:e.slice(d,e.indexOf("<",d))}),0===i&&r.push(t),(u=a[i-1])&&u.children.push(t),a[i]=t),(!l||t.voidElement)&&(i>-1&&(t.voidElement||t.name===s.slice(2,-1))&&(i--,t=-1===i?r:a[i]),!o&&"<"!==m&&m)){u=-1===i?r:a[i].children;var v=e.indexOf("<",d),y=e.slice(d,-1===v?void 0:v);g.test(y)&&(y=" "),(v>-1&&i+u.length>=0||" "!==y)&&u.push({type:"text",content:y})}})),r};function v(){if(console&&console.warn){for(var e,n=arguments.length,t=new Array(n),r=0;r2&&void 0!==arguments[2]?arguments[2]:{},r=n.languages[0],a=!!n.options&&n.options.fallbackLng,i=n.languages[n.languages.length-1];if("cimode"===r.toLowerCase())return!0;var o=function(e,t){var r=n.services.backendConnector.state["".concat(e,"|").concat(t)];return-1===r||2===r};return!(t.bindI18n&&t.bindI18n.indexOf("languageChanging")>-1&&n.services.backendConnector.backend&&n.isLanguageChangingTo&&!o(n.isLanguageChangingTo,e))&&(!!n.hasResourceBundle(r,e)||(!(n.services.backendConnector.backend&&(!n.options.resources||n.options.partialBundledLanguages))||!(!o(r,e)||a&&!o(i,e))))}function w(e,n){var t=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!n.languages||!n.languages.length)return b("i18n.languages were undefined or empty",n.languages),!0;var r=void 0!==n.options.ignoreJSONStructure;return r?n.hasLoadedNamespace(e,{precheck:function(n,r){if(t.bindI18n&&t.bindI18n.indexOf("languageChanging")>-1&&n.services.backendConnector.backend&&n.isLanguageChangingTo&&!r(n.isLanguageChangingTo,e))return!1}}):x(e,n,t)}function j(e){return e.displayName||e.name||("string"==typeof e&&e.length>0?e:"Unknown")}var S,E=/&(?:amp|#38|lt|#60|gt|#62|apos|#39|quot|#34|nbsp|#160|copy|#169|reg|#174|hellip|#8230|#x2F|#47);/g,N={"&":"&","&":"&","<":"<","<":"<",">":">",">":">","'":"'","'":"'",""":'"',""":'"'," ":" "," ":" ","©":"©","©":"©","®":"®","®":"®","…":"…","…":"…","/":"/","/":"/"},k=function(e){return N[e]},I={bindI18n:"languageChanged",bindI18nStore:"",transEmptyNodeValue:"",transSupportBasicHtmlNodes:!0,transWrapTextNodes:"",transKeepBasicHtmlNodesFor:["br","strong","i","p"],useSuspense:!0,unescape:function(e){return e.replace(E,k)}};function P(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};I=r(r({},I),e)}function R(){return I}function C(e){S=e}function T(){return S}var A=["format"],L=["children","count","parent","i18nKey","context","tOptions","values","defaults","components","ns","i18n","t","shouldUnescape"];function U(e,n){if(!e)return!1;var t=e.props?e.props.children:e.children;return n?t.length>0:!!t}function z(e){return e?e.props?e.props.children:e.children:[]}function B(e){return Array.isArray(e)?e:[e]}function K(e,t,i,o,s,c){if(""===t)return[];var u=o.transKeepBasicHtmlNodesFor||[],l=t&&new RegExp(u.join("|")).test(t);if(!e&&!l)return[t];var f={};!function e(t){B(t).forEach((function(t){"string"!=typeof t&&(U(t)?e(z(t)):"object"!==a(t)||n.isValidElement(t)||Object.assign(f,t))}))}(e);var p=h("<0>".concat(t,"")),d=r(r({},f),s);function g(e,t,r){var a=z(e),i=v(a,t.children,r);return function(e){return"[object Array]"===Object.prototype.toString.call(e)&&e.every((function(e){return n.isValidElement(e)}))}(a)&&0===i.length?a:i}function m(e,t,a,i,o){e.dummy&&(e.children=t),a.push(n.cloneElement(e,r(r({},e.props),{},{key:i}),o?void 0:t))}function v(t,s,f){var p=B(t);return B(s).reduce((function(t,s,h){var y,b,O,x=s.children&&s.children[0]&&s.children[0].content&&i.services.interpolator.interpolate(s.children[0].content,d,i.language);if("tag"===s.type){var w=p[parseInt(s.name,10)];!w&&1===f.length&&f[0][s.name]&&(w=f[0][s.name]),w||(w={});var j=0!==Object.keys(s.attrs).length?(y={props:s.attrs},(O=r({},b=w)).props=Object.assign(y.props,b.props),O):w,S=n.isValidElement(j),E=S&&U(s,!0)&&!s.voidElement,N=l&&"object"===a(j)&&j.dummy&&!S,k="object"===a(e)&&null!==e&&Object.hasOwnProperty.call(e,s.name);if("string"==typeof j){var I=i.services.interpolator.interpolate(j,d,i.language);t.push(I)}else if(U(j)||E){m(j,g(j,s,f),t,h)}else if(N){var P=v(p,s.children,f);t.push(n.cloneElement(j,r(r({},j.props),{},{key:h}),P))}else if(Number.isNaN(parseFloat(s.name))){if(k)m(j,g(j,s,f),t,h,s.voidElement);else if(o.transSupportBasicHtmlNodes&&u.indexOf(s.name)>-1)if(s.voidElement)t.push(n.createElement(s.name,{key:"".concat(s.name,"-").concat(h)}));else{var R=v(p,s.children,f);t.push(n.createElement(s.name,{key:"".concat(s.name,"-").concat(h)},R))}else if(s.voidElement)t.push("<".concat(s.name," />"));else{var C=v(p,s.children,f);t.push("<".concat(s.name,">").concat(C,""))}}else if("object"!==a(j)||S)1===s.children.length&&x?t.push(n.cloneElement(j,r(r({},j.props),{},{key:h}),x)):t.push(n.cloneElement(j,r(r({},j.props),{},{key:h})));else{var T=s.children[0]?x:null;T&&t.push(T)}}else if("text"===s.type){var A=o.transWrapTextNodes,L=c?o.unescape(i.services.interpolator.interpolate(s.content,d,i.language)):i.services.interpolator.interpolate(s.content,d,i.language);A?t.push(n.createElement(A,{key:"".concat(s.name,"-").concat(h)},L)):t.push(L)}return t}),[])}return z(v([{dummy:!0,children:e||[]}],p,B(e||[]))[0])}function V(e){var t=e.children,i=e.count,o=e.parent,c=e.i18nKey,u=e.context,l=e.tOptions,f=void 0===l?{}:l,p=e.values,d=e.defaults,g=e.components,m=e.ns,h=e.i18n,y=e.t,O=e.shouldUnescape,x=s(e,L),w=h||T();if(!w)return b("You will need to pass in an i18next instance by using i18nextReactModule"),t;var j=y||w.t.bind(w)||function(e){return e};u&&(f.context=u);var S=r(r({},R()),w.options&&w.options.react),E=m||j.ns||w.options&&w.options.defaultNS;E="string"==typeof E?[E]:E||["translation"];var N=d||function e(t,r){if(!t)return"";var i="",o=B(t),c=r.transSupportBasicHtmlNodes&&r.transKeepBasicHtmlNodesFor?r.transKeepBasicHtmlNodesFor:[];return o.forEach((function(t,o){if("string"==typeof t)i+="".concat(t);else if(n.isValidElement(t)){var u=Object.keys(t.props).length,l=c.indexOf(t.type)>-1,f=t.props.children;if(!f&&l&&0===u)i+="<".concat(t.type,"/>");else if(f||l&&0===u)if(t.props.i18nIsDynamicList)i+="<".concat(o,">");else if(l&&1===u&&"string"==typeof f)i+="<".concat(t.type,">").concat(f,"");else{var p=e(f,r);i+="<".concat(o,">").concat(p,"")}else i+="<".concat(o,">")}else if(null===t)v("Trans: the passed in value is invalid - seems you passed in a null child.");else if("object"===a(t)){var d=t.format,g=s(t,A),m=Object.keys(g);if(1===m.length){var h=d?"".concat(m[0],", ").concat(d):m[0];i+="{{".concat(h,"}}")}else v("react-i18next: the passed in object contained more than one variable - the object should look like {{ value, format }} where format is optional.",t)}else v("Trans: the passed in value is invalid - seems you passed in a variable like {number} - please pass in variables for interpolation as full objects like {{number}}.",t)})),i}(t,S)||S.transEmptyNodeValue||c,k=S.hashTransKey,I=c||(k?k(N):N),P=p?f.interpolation:{interpolation:r(r({},f.interpolation),{},{prefix:"#$?",suffix:"?$#"})},C=r(r(r(r({},f),{},{count:i},p),P),{},{defaultValue:N,ns:E}),U=K(g||t,I?j(I,C):N,w,S,C,O),z=void 0!==o?o:S.defaultTransParent;return z?n.createElement(z,x,U):U}var D={type:"3rdParty",init:function(e){P(e.options.react),C(e)}},F=n.createContext(),H=function(){function e(){!function(e,n){if(!(e instanceof n))throw new TypeError("Cannot call a class as a function")}(this,e),this.usedNamespaces={}}var n,t,r;return n=e,(t=[{key:"addUsedNamespaces",value:function(e){var n=this;e.forEach((function(e){n.usedNamespaces[e]||(n.usedNamespaces[e]=!0)}))}},{key:"getUsedNamespaces",value:function(){return Object.keys(this.usedNamespaces)}}])&&i(n.prototype,t),r&&i(n,r),e}();function W(e){return function(n){return new Promise((function(t){var a=M();e.getInitialProps?e.getInitialProps(n).then((function(e){t(r(r({},e),a))})):t(a)}))}}function M(){var e=T(),n=e.reportNamespaces?e.reportNamespaces.getUsedNamespaces():[],t={},r={};return e.languages.forEach((function(t){r[t]={},n.forEach((function(n){r[t][n]=e.getResourceBundle(t,n)||{}}))})),t.initialI18nStore=r,t.initialLanguage=e.language,t}var $=["children","count","parent","i18nKey","context","tOptions","values","defaults","components","ns","i18n","t","shouldUnescape"];var q=function(e,t){var r=n.useRef();return n.useEffect((function(){r.current=t?r.current:e}),[e,t]),r.current};function Y(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=t.i18n,o=n.useContext(F)||{},s=o.i18n,u=o.defaultNS,l=i||s||T();if(l&&!l.reportNamespaces&&(l.reportNamespaces=new H),!l){b("You will need to pass in an i18next instance by using initReactI18next");var f=function(e,n){return"string"==typeof n?n:n&&"object"===a(n)&&"string"==typeof n.defaultValue?n.defaultValue:Array.isArray(e)?e[e.length-1]:e},p=[f,{},!1];return p.t=f,p.i18n={},p.ready=!1,p}l.options.react&&void 0!==l.options.react.wait&&b("It seems you are still using the old wait option, you may migrate to the new useSuspense behaviour.");var d=r(r(r({},R()),l.options.react),t),g=d.useSuspense,m=d.keyPrefix,h=e||u||l.options&&l.options.defaultNS;h="string"==typeof h?[h]:h||["translation"],l.reportNamespaces.addUsedNamespaces&&l.reportNamespaces.addUsedNamespaces(h);var v=(l.isInitialized||l.initializedStoreOnce)&&h.every((function(e){return w(e,l,d)}));function y(){return l.getFixedT(t.lng||null,"fallback"===d.nsMode?h:h[0],m)}var x=n.useState(y),j=c(x,2),S=j[0],E=j[1],N=h.join(),k=q(N),I=n.useRef(!0);n.useEffect((function(){var e=d.bindI18n,n=d.bindI18nStore;function t(){I.current&&E(y)}return I.current=!0,v||g||O(l,h,(function(){I.current&&E(y)})),v&&k&&k!==N&&I.current&&E(y),e&&l&&l.on(e,t),n&&l&&l.store.on(n,t),function(){I.current=!1,e&&l&&e.split(" ").forEach((function(e){return l.off(e,t)})),n&&l&&n.split(" ").forEach((function(e){return l.store.off(e,t)}))}}),[l,N]);var P=n.useRef(!0);n.useEffect((function(){I.current&&!P.current&&E(y),P.current=!1}),[l,m]);var C=[S,l,v];if(C.t=S,C.i18n=l,C.ready=v,v)return C;if(!v&&!g)return C;throw new Promise((function(e){O(l,h,(function(){e()}))}))}var _=["forwardedRef"];var J=["ns","children"];function Z(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},a=r.i18n,i=n.useContext(F)||{},o=i.i18n,s=a||o||T();s.options&&s.options.isClone||(e&&!s.initializedStoreOnce&&(s.services.resourceStore.data=e,s.options.ns=Object.values(e).reduce((function(e,n){return Object.keys(n).forEach((function(n){e.indexOf(n)<0&&e.push(n)})),e}),s.options.ns),s.initializedStoreOnce=!0,s.isInitialized=!0),t&&!s.initializedLanguageOnce&&(s.changeLanguage(t),s.initializedLanguageOnce=!0))}var G=["initialI18nStore","initialLanguage"];e.I18nContext=F,e.I18nextProvider=function(e){var t=e.i18n,r=e.defaultNS,a=e.children,i=n.useMemo((function(){return{i18n:t,defaultNS:r}}),[t,r]);return n.createElement(F.Provider,{value:i},a)},e.Trans=function(e){var t=e.children,a=e.count,i=e.parent,o=e.i18nKey,c=e.context,u=e.tOptions,l=void 0===u?{}:u,f=e.values,p=e.defaults,d=e.components,g=e.ns,m=e.i18n,h=e.t,v=e.shouldUnescape,y=s(e,$),b=n.useContext(F)||{},O=b.i18n,x=b.defaultNS,w=m||O||T(),j=h||w&&w.t.bind(w);return V(r({children:t,count:a,parent:i,i18nKey:o,context:c,tOptions:l,values:f,defaults:p,components:d,ns:g||j&&j.ns||x||w&&w.options&&w.options.defaultNS,i18n:w,t:h,shouldUnescape:v},y))},e.TransWithoutContext=V,e.Translation=function(e){var n=e.ns,t=e.children,r=c(Y(n,s(e,J)),3),a=r[0],i=r[1],o=r[2];return t(a,{i18n:i,lng:i.language},o)},e.composeInitialProps=W,e.date=function(){return""},e.getDefaults=R,e.getI18n=T,e.getInitialProps=M,e.initReactI18next=D,e.number=function(){return""},e.plural=function(){return""},e.select=function(){return""},e.selectOrdinal=function(){return""},e.setDefaults=P,e.setI18n=C,e.time=function(){return""},e.useSSR=Z,e.useTranslation=Y,e.withSSR=function(){return function(e){function t(t){var a=t.initialI18nStore,i=t.initialLanguage,o=s(t,G);return Z(a,i),n.createElement(e,r({},o))}return t.getInitialProps=W(e),t.displayName="withI18nextSSR(".concat(j(e),")"),t.WrappedComponent=e,t}},e.withTranslation=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function(a){function i(i){var o=i.forwardedRef,u=s(i,_),l=c(Y(e,r(r({},u),{},{keyPrefix:t.keyPrefix})),3),f=l[0],p=l[1],d=l[2],g=r(r({},u),{},{t:f,i18n:p,tReady:d});return t.withRef&&o?g.ref=o:!t.withRef&&o&&(g.forwardedRef=o),n.createElement(a,g)}i.displayName="withI18nextTranslation(".concat(j(a),")"),i.WrappedComponent=a;return t.withRef?n.forwardRef((function(e,t){return n.createElement(i,Object.assign({},e,{forwardedRef:t}))})):i}},Object.defineProperty(e,"__esModule",{value:!0})})); diff --git a/src/useTranslation.js b/src/useTranslation.js index 44bed289..8f4b6ec7 100644 --- a/src/useTranslation.js +++ b/src/useTranslation.js @@ -58,7 +58,7 @@ export function useTranslation(ns, props = {}) { // binding t function to namespace (acts also as rerender trigger) function getT() { return i18n.getFixedT( - null, + props.lng || null, i18nOptions.nsMode === 'fallback' ? namespaces : namespaces[0], keyPrefix, ); diff --git a/test/useTranslation.spec.js b/test/useTranslation.spec.js index 152d43b5..a379b0fc 100644 --- a/test/useTranslation.spec.js +++ b/test/useTranslation.spec.js @@ -160,4 +160,44 @@ describe('useTranslation', () => { expect(t2('key1')).toBe('test2'); }); }); + + describe('with lng prop', () => { + i18nInstance.addResource('en', 'translation', 'myKey', 'second test'); + i18nInstance.addResource('fr', 'translation', 'myKey', 'deuxième essai'); + i18nInstance.addResource('it', 'translation', 'myKey', 'secondo test'); + const wrapper = ({ children, i18n }) => ( + {children} + ); + + it('should render correct content', () => { + const { result: resultNoLng } = renderHook(() => useTranslation('translation'), { + wrapper, + initialProps: { + i18n: i18nInstance, + }, + }); + const { t: t1 } = resultNoLng.current; + expect(t1('myKey')).toBe('second test'); + + const { result: resultIt } = renderHook(() => useTranslation('translation', { lng: 'it' }), { + wrapper, + initialProps: { + i18n: i18nInstance, + }, + }); + + const { t: t2 } = resultIt.current; + expect(t2('myKey')).toBe('secondo test'); + + const { result: resultFr } = renderHook(() => useTranslation('translation', { lng: 'fr' }), { + wrapper, + initialProps: { + i18n: i18nInstance, + }, + }); + + const { t: t3 } = resultFr.current; + expect(t3('myKey')).toBe('deuxième essai'); + }); + }); });