i18next - REACT - Firefox returns "de" - Chrome returns "de-DE" - reactjs

using
"i18next": "^21.6.6",
"i18next-browser-languagedetector": "^6.1.2",
"i18next-http-backend": "^1.3.2"
I got the following folder & files:
"public/locales/de-DE/*.json"
"public/locales/en-US/*.json"
Problem:
In Chrome, first visiting the website, the navigator.language returns "de-DE". The language is found correctly. But default of Firefox returns "de" without the region. So, i18next does not find the matching folder.
Whats the best way to map "non-region" codes to an "default-region" for a language, e.g. de -> de-DE or en -> en-US
Is there something specified by i18next or shall I just copy all from de-DE to de folder?
Configuration:
i18n
.use(Backend)
.use(LanguageDetector)
.use(initReactI18next)
.init({
fallbackLng: 'en-US',
debug: true,
interpolation: {
escapeValue: false,
},
react: {
useSuspense: false,
},
});

Rename your folders to en and de, and set the load option to languageOnly.

Related

i18next interpolation defaultVariables from backend

I have the following i18n setup on my react
import i18n from 'i18next'
import LanguageDetector from 'i18next-browser-languagedetector'
import {initReactI18next} from 'react-i18next'
import Backend from 'i18next-http-backend';
i18n
.use(initReactI18next)
.use(LanguageDetector)
.use(Backend)
.init({
backend: {
loadPath: `test.com`,
},
react: {
useSuspense: false
},
whitelist: ['en', 'fr', 'es'],
fallbackLng: ['en'],
detection: {
order: ['cookie', 'navigator'],
lookupCookie: 'i18nextLng',
caches: ['cookie'],
cookieOptions: { path: '/', sameSite: 'strict' },
checkWhitelist: true
}
})
export default i18n
I have a unique product with some information as price I would like to use as defaultVariables
Reading the doc I can change the inti config adding
{
interpolation: {
defaultVariables: {price: 100}
}
}
and then {{price}} should be available on all my translations
This part is working great.
But I am getting the product from a server call and I can not find any way to update the defaultVariables once i18n has been initialized
Officially, the only way to have defaultVariables injected is via init function.
This means you have to load those values before calling init(), and then pass them via init options.
But....
you can try to do this:
i18next.services.interpolator.options.interpolation.defaultVariables = { price: 100 }
This may work, but this is for sure unsupported and not recommended.
btw: the whitelist option was replaced with supportedLngs: https://www.i18next.com/misc/migration-guide#removed-deprecated

i18next get 404 response when there is no translation file

I'm using i18next-http-backend to get translations.
Translation files:
en.json
pt.json
pt-BR.json
This is my config:
.init({
fallbackLng: 'en',
supportedLngs: ['en', 'pt', 'pt-BR'],
nonExplicitSupportedLngs: true,
backend: {
backends: [
LocalStorageBackend, // primary
HttpBackend, // fallback
],
backendOptions: [
{
prefix: 'i18next_res_',
defaultVersion: version,
},
{
loadPath: '${some-path}/{{ns}}/{{lng}}.json',
addPath: '${some-path}/{{ns}}/{{lng}}',
queryStringParams: { v: version },
},
],
},
})
If the browser language is English (United States) en-US I get the 404 Not Found error and then en is loaded.
When I add load: 'languageOnly' to the config, there is no 404, but in this case it is not possible to load pt-BR languege. Instead pt is loaded.
I looked through the documentation, but did not find an option to fix this behavior.
comment of the "i18next" library developer:
"so if there is no en-US, but there is en and you're using load: 'all' or no load option, the en resources will be loaded. But before this, i18next tries to fetch en-US and if there are no en-US resources you'll see a 404...
If you do not like to "see" those 404 requests, you need to list all languages in the supportedLngs option and not set nonExplicitSupportedLngs: true
Said in other words: if you use nonExplicitSupportedLngs: true you can't prevent all 404"

The Components are disappearing after importing i18n in my App component

Created i18n.js file as it is said in documentary , and inserted in the file the following code
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import Backend from 'i18next-http-backend';
import LanguageDetector from 'i18next-browser-languagedetector';
const languages = ["en", "es", "ar"]
const options = {
order: [ 'localStorage', 'cookie', 'querystring', , 'sessionStorage', 'navigator', 'htmlTag', 'path', 'subdomain'],
lookupQuerystring: 'lng',
lookupCookie: 'i18next',
lookupLocalStorage: 'i18nextLng',
lookupSessionStorage: 'i18nextLng',
lookupFromPathIndex: 0,
lookupFromSubdomainIndex: 0,
caches: ['localStorage', 'cookie'],
excludeCacheFor: ['cimode'],
cookieMinutes: 10,
cookieDomain: 'myDomain',
htmlTag: document.documentElement,
cookieOptions: { path: '/', sameSite: 'strict' }
}
i18n
.use(Backend)
.use(LanguageDetector)
.use(initReactI18next)
.init({
fallbackLng: 'en',
lng: 'en',
debug: true,
whitelist: languages,
detection: options,
interpolation: {
escapeValue: false,
}
});
export default i18n;
then imported above mentioned file in App component,
After refreshing the already translated pages, the components are disappearing, but when i am comment i18n.js imported file in my App component out everything is working
Please check the browsers console, probably you will find an answer there.
From a quick look at your code, it seems that your options object has a type error inside order array, an extra comma.
..., 'querystring', , 'sessionStorage', ...
I would suggest to use eslint so you can find and fix this issues in your IDE.

i18next not loading in file from public folder

I am trying to load multiple translation files to react app.
So far, I've been able to seperate the files
was having issues with it trying to append the name of two different translations file -- /locales/{{lng}}/{{ns}}.json?lng=en+es&ns=translation1+translation2)
I have solved this but now it will not read from the public folder
my config file looks like the following
import i18n from 'i18next'
import Backend from 'i18next-http-backend'
import Http from 'i18next-http-backend'
import { initReactI18next } from 'react-i18next'
import BackendAdapter from 'i18next-multiload-backend-adapter'
const languages = ['en', 'es']
i18n
.use(Backend)
.use(initReactI18next)
.init({
defaultNS: 'menus',
fallbackLng: 'en',
debug: true,
whitelist: languages,
lng: 'en',
backend: {
backends:[
new BackEndAdapter(null, {
backend: new Http(null,{
loadPath: `${process.env.PUBLIC_URL}/locales/{{lng}}/{{ns}}.json?lng={{lng}}&{{ns}}`,
addPath: `${process.env.PUBLIC_URL}/locales/add/{{lng}}/{{ns}}`,
allowMultiLoading: true
})
})
]
},
interpolation: {
escapeValue: false
}
})
export default i18n
package.json
{
"i18next": "^19.5.1",
"i18next-http-backend": "^1.0.15",
"i18next-multiload-backend-adapter": "^1.0.0"
}
using this as reference as to why multiload adapter is needed
It should look like this:
import i18n from 'i18next';
import HttpBackend from 'i18next-http-backend';
import { initReactI18next } from 'react-i18next';
const languages = ['en', 'es'];
i18n
.use(HttpBackend)
.use(initReactI18next)
.init({
defaultNS: 'menus',
fallbackLng: 'en',
debug: true,
whitelist: languages,
lng: 'en',
backend: {
loadPath: `${process.env.PUBLIC_URL}/locales/{{lng}}/{{ns}}.json?lng={{lng}}&{{ns}}`,
addPath: `${process.env.PUBLIC_URL}/locales/add/{{lng}}/{{ns}}`,
},
interpolation: {
escapeValue: false,
},
});
export default i18n;

Netlify build passed but shows only html css

I need help on netlify deployments. Actually it deploys and shows "Published" but I tried Gatsby build and nothing related to fail or any netlify failed deployment but once it is published in Live then it only shows html & css.
Navbar menu and dropdowns doesn't works. But in localhost, it shows everythings.
I don't understand why after Netlify deployment the website doesn't looks like my local.
Dev console shows these warnings:
-React-Hot-Loader: react-🔥-dom patch is not detected. React 16.6+ features may not work.
-You may be attempting to nest <Helmet> components within each other, which is not allowed. Refer to our API for more information.
-Warning: componentWillMount has been renamed, and is not recommended for use. See https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html for details.
What I tried:
-Check old commits.
-Check public folder in local apache server.
-Clear gatsby cache, netlify cache and redeploy.
Nothing worked if you got any idea I would like to test please
Here is the gatsby log:
gatsby build
success open and validate gatsby-configs - 0.111s
success load plugins - 1.952s
success onPreInit - 0.034s
success delete html and css files from previous builds - 0.049s
success initialize cache - 0.009s
success copy gatsby files - 0.113s
success onPreBootstrap - 0.015s
success createSchemaCustomization - 0.008s
-> wordpress__wp_v2 fetched : 1
-> wordpress__wp_example.wordpress.com fetched : 1
Path: /wp/v2/sites/example.wordpress.com/jetpack-global-styles?per_page=100&page=1
The server response was "403 Forbidden"
Inner exception message: "Sorry, you are not allowed to do that."
-> wordpress__POST fetched : 59
-> wordpress__PAGE fetched : 2
-> wordpress__wp_media fetched : 90
-> wordpress__wp_blocks fetched : 1
-> wordpress__wp_feedback fetched : 0
-> wordpress__wp_jp_pay_order fetched : 0
-> wordpress__wp_jp_pay_product fetched : 0
-> wordpress__wp_block_areas fetched : 0
-> wordpress__wp_types fetched : 1
-> wordpress__wp_statuses fetched : 1
-> wordpress__wp_taxonomies fetched : 1
-> wordpress__CATEGORY fetched : 13
-> wordpress__TAG fetched : 7
-> wordpress__wp_users fetched : 2
-> wordpress__wp_me fetched : 1
-> wordpress__wp_comments fetched : 0
-> wordpress__wp_search fetched : 61
-> wordpress__wp_settings fetched : 1
Path: /wp/v2/sites/example.wordpress.com/themes?per_page=100&page=1
The server response was "400 Bad Request"
Inner exception message: "Missing parameter(s): status"
success source and transform nodes - 15.832s
warn Multiple node fields resolve to the same GraphQL field `wordpress__wp_media.guid` - [`guid`, `guid___NODE`].
warn Multiple node fields resolve to the same GraphQL field `wordpress__POST.jetpack_featured_media_url` -
success building schema - 1.044s
success createPages - 0.149s
warn Non-deterministic routing danger: Attempting to create page: "/contact/", but page "/contact" already exists
This could lead to non-deterministic routing behavior
success createPagesStatefully - 0.244s
success onPreExtractQueries - 0.003s
success update schema - 0.055s
success extract queries from components - 0.755s
success write out requires - 0.010s
success write out redirect data - 0.005s
success Build manifest and related icons - 0.168s
success onPostBootstrap - 0.194s
â €
info bootstrap finished - 29.155 s
â €
success Building production JavaScript and CSS bundles - 59.710s
success Rewriting compilation hashes - 0.005s
success run queries - 61.016s - 97/97 1.59/s
[ ] 0.001 s 0/98 0% Building static HTML for pages
i18next: languageChanged en
i18next: languageChanged en
i18next: initialized {
debug: true,
initImmediate: true,
ns: [ 'translation' ],
defaultNS: 'translation',
fallbackLng: [ 'en' ],
fallbackNS: false,
whitelist: false,
nonExplicitWhitelist: false,
load: 'languageOnly',
preload: false,
simplifyPluralSuffix: true,
keySeparator: '.',
nsSeparator: ':',
pluralSeparator: '_',
contextSeparator: '_',
partialBundledLanguages: false,
saveMissing: false,
updateMissing: false,
saveMissingTo: 'fallback',
saveMissingPlurals: true,
missingKeyHandler: false,
missingInterpolationHandler: false,
postProcess: false,
returnNull: true,
returnEmptyString: true,
returnObjects: false,
joinArrays: false,
returnedObjectHandler: [Functi18next: initialized {
debug: true,
initImmediate: true,
ns: [ 'translation' ],
defaultNS: 'translation',
fallbackLng: [ 'en' ],
fallbackNS: false,
whitelist: false,
nonExplicitWhitelist: false,
load: 'languageOnly',
preload: false,
simplifyPluralSuffix: true,
keySeparator: '.',
nsSeparator: ':',
pluralSeparator: '_',
contextSeparator: '_',
partialBundledLanguages: false,
saveMissing: false,
updateMissing: false,
saveMissingTo: 'fallback',
saveMissingPlurals: true,
missingKeyHandler: false,
missingInterpolationHandler: false,
postProcess: false,
returnNull: true,
returnEmptyString: true,
returnObjects: false,
joinArrays: false,
returnedObjectHandler: [Function: returnedObjectHandler],
parseMissingKeyHandler: false,
appendNamespaceToMissingKey: false,
appendNamespaceToCIMode: false,
overloadTranslationOptionHandler: [Function: handle],
interpolation: { escapeValue: false },
resources: { en: { translation: [Object] }, fr: { translation: [Object] } },
react: { wait: true, nsMode: 'default' }
}
ion: returnedObjectHandler],
parseMissingKeyHandler: false,
appendNamespaceToMissingKey: false,
appendNamespaceToCIMode: false,
overloadTranslationOptionHandler: [Function: handle],
interpolation: { escapeValue: false },
resources: { en: { translation: [Object] }, fr: { translation: [Object] } },
react: { wait: true, nsMode: 'default' }
[============== ] 11.817 s 50/98 51% Building static HTML for pages
success Building static HTML for pages - 12.124s - 98/98 8.08/s
success onPostBuild - 0.381s
info Done building in 103.31746359 sec
Edit:
This installation solved my issue :)
npm install #hot-loader/react-dom

Resources