{"_id":"@autushka/next-translate","_rev":"1-4d7469832703927d87ab283dee6d5c10","name":"@autushka/next-translate","dist-tags":{"latest":"0.16.0-canary.3"},"versions":{"0.16.0-canary.3":{"name":"@autushka/next-translate","version":"0.16.0-canary.3","description":"Next.js utility to translate pages without the need of a server (static i18n pages generator).","license":"MIT","keywords":["react","i18n","nextjs","next.js","next","translation","localization","locale","static"],"repository":{"type":"git","url":"https://github.com/vinissimus/next-translate.git"},"author":{"name":"Aral Roca Gòmez","email":"contact@aralroca.com"},"scripts":{"build":"yarn clean && cross-env NODE_ENV=production babel src -d .","clean":"rm -f *.js && yarn clean:examples","clean:examples":"rm -rf examples/**/.next && rm -rf examples/**/node_modules && rm -rf examples/**/yarn.lock","example:static-site":"yarn build && cd examples/static-site && yarn && yarn dev","example:with-server":"yarn build && cd examples/with-server && yarn && yarn dev","example:with-dynamic-routes":"yarn build && cd examples/with-dynamic-routes && yarn && yarn dev","format":"pretty-quick","prepublish":"yarn test && yarn build","test":"cross-env NODE_ENV=test jest","test:coverage":"cross-env NODE_ENV=test jest --coverage","test:watch":"cross-env NODE_ENV=test jest --watch"},"bin":{"next-translate":"./cli/builder.js"},"devDependencies":{"@babel/cli":"7.8.4","@babel/core":"7.9.6","@babel/preset-env":"7.9.6","@testing-library/react":"10.0.4","babel-jest":"26.0.1","babel-plugin-transform-es2015-modules-commonjs":"6.26.2","babel-preset-minify":"0.5.1","cross-env":"7.0.2","express":"4.17.1","husky":"4.2.5","jest":"26.0.1","next":"9.3.6","prettier":"2.0.5","pretty-quick":"2.0.1","react":"16.13.1","react-dom":"16.13.1","supertest":"4.0.2"},"peerDependencies":{"next":">= 9.3.0","react":">= 16.8.0"},"husky":{"hooks":{"pre-commit":"pretty-quick --staged && yarn test"}},"prettier":{"trailingComma":"es5","tabWidth":2,"semi":false,"singleQuote":true},"jest":{"roots":["<rootDir>/__tests__","<rootDir>/src"],"transform":{"^.+\\.jsx?$":"babel-jest"}},"licenseText":"The MIT License\n\nMIT License\n\nCopyright (c) 2019 Aral Roca Gomez\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n© 2019 GitHub, Inc.","_id":"@autushka/next-translate@0.16.0-canary.3","dist":{"shasum":"4d209756806fb8a3943488f073f0446fcce64a2c","integrity":"sha512-b93xyNDdt2Hsu9eE+0cOQaPpIukWfeYmu39pyVSsh1kH3oo4Bc6r6AJsEgukG0KzY0eKsddPu0NFdeeLAko1lA==","tarball":"https://registry.npmjs.org/@autushka/next-translate/-/next-translate-0.16.0-canary.3.tgz","fileCount":50,"unpackedSize":85350,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJeuBMvCRA9TVsSAnZWagAAnRcP/RXOw7nGXCTexFmMg6Da\n5XVFqsfDO7Pzwd26z1YVsgbvnBL/NJHzZWEIMbiVK8/4A4U0iGjJCykFxdAX\nVjTXkuCuMLPLccOgJVxSm2NSSEQ6XgFyxgxy2j1k8TlriluUlGSqNgcUpNvY\n2Ixm+9iXa15sBgQqXz2SKTJVgZ1x5aKvpSvlLpTZs9bJPxW9x9LdFFDtrfL+\nmS6QD5Tjxe95Y4KbZPNBnH6RoA03/3jhpQ9WCZx3adzNMzUmsd/LJ/iSbrtq\nqzF0qZYk5TDsZeobldCMZFFwrKVJWPost0qYHQZC1g5PoeuoMlqhUsddkkFg\noOH7jKLuMhbDvVeBtqTS90ihFBE7Tfz9WOpufgwmJIMxONbkMcxLOqHOHe/a\nF14iHrWPv+UaigLgO0/FbLPoV9JS8cCAu/KREm/eG4nLrv/jei1TRiUinIBh\nf+h+RJFtlzfAduxG6ybpu9ByZmqXF+1GWmMSaFOnQ9YGOfbgZI0isGNiu+q8\nquw/BIrb/0Uz4KDqmeGhCz+9KkF0c4+H2HP1JkegwNFMu502bApq3YmNzjLL\nnvoooFbinw/o3h//6OsCaEjG50qyHj9CnpIe9F87qwh8PefCiN+daQEJJ2Is\nrKyV+1YY1Oup1yAgGuMmuCXAEvFRX1/17N/mBF+2wmETJiRjeX1OLBCwusZw\nV/+5\r\n=AVnh\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCIA+xDzvklpRBQ1odFsSuQH5E6VtUYIzmjvbZpDaQdwlzAiAce5eN5ZYgoYYrSFBmfvG3sgMqnHhuqr7sHGfwb36Siw=="}]},"maintainers":[{"name":"autushka","email":"aleh.autushka@gmail.com"}],"_npmUser":{"name":"autushka","email":"aleh.autushka@gmail.com"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/next-translate_0.16.0-canary.3_1589121838697_0.16681630833214656"},"_hasShrinkwrap":false}},"time":{"created":"2020-05-10T14:43:58.663Z","0.16.0-canary.3":"2020-05-10T14:43:58.897Z","modified":"2022-04-04T16:41:25.703Z"},"maintainers":[{"name":"autushka","email":"aleh.autushka@gmail.com"}],"description":"Next.js utility to translate pages without the need of a server (static i18n pages generator).","keywords":["react","i18n","nextjs","next.js","next","translation","localization","locale","static"],"repository":{"type":"git","url":"https://github.com/vinissimus/next-translate.git"},"author":{"name":"Aral Roca Gòmez","email":"contact@aralroca.com"},"license":"MIT","readme":"<p align=\"center\">\n    <img src=\"images/logo.svg\" width=\"300\" alt=\"next-translate\" />\n</p>\n\n<p align=\"center\">\n    <b>i18n</b> for Next.js | ○  (Static)  | ●  (SSG) | λ  (Server)\n</p>\n\n<div align=\"center\">\n\n[![npm version](https://badge.fury.io/js/next-translate.svg)](https://badge.fury.io/js/next-translate)\n[![PRs Welcome][badge-prwelcome]][prwelcome]\n[![Join the community on Spectrum](https://withspectrum.github.io/badge/badge.svg)][spectrum]\n\n</div>\n\n- [1. About next-translate](#1-about-next-translate)\n  - [How is this lib handling the routes?](#how-is-this-lib-handling-the-routes)\n- [2. Getting started](#2-getting-started)\n  - [Install](#install)\n  - [Use translations in your pages](#use-translations-in-your-pages)\n  - [Add pages to .gitignore](#add-pages-to-gitignore)\n- [3. Translation JSONs folder](#3-translation-jsons-folder)\n- [4. Configuration](#4-configuration)\n- [5. API](#5-api)\n  - [useTranslation](#usetranslation)\n  - [withTranslation](#withtranslation)\n  - [Trans Component](#trans-component)\n  - [appWithI18n](#appwithi18n)\n  - [DynamicNamespaces](#dynamicnamespaces)\n  - [I18nProvider](#i18nprovider)\n  - [i18nMiddleware](#i18nmiddleware)\n  - [Link](#link)\n  - [Router](#router)\n  - [clientSideLang](#clientsidelang)\n- [6. Plurals](#6-plurals)\n- [7. Use HTML inside the translation](#7-use-html-inside-the-translation)\n- [8. Nested translations](#8-nested-translations)\n- [9. How to change the language](#9-how-to-change-the-language)\n- [10. Get language in the special Next.js functions](#10-get-language-in-the-special-nextjs-functions)\n  - [getStaticProps](#getstaticprops)\n  - [getStaticPaths](#getstaticpaths)\n  - [getServerSideProps](#getserversideprops)\n  - [getInitialProps](#getinitialprops)\n- [11 How to use multi-language in a page](#11-how-to-use-multi-language-in-a-page)\n- [12. Do I need this \"build step\"? Is there an alternative?](#12-do-i-need-this-build-step-is-there-an-alternative)\n- [13. Demos](#13-demos)\n  - [Using the \"build step\"](#using-the-build-step)\n  - [Using an alternative to the \"build step\": dynamic routes](#using-an-alternative-to-the-build-step-dynamic-routes)\n  - [Using an alternative to the \"build step\": custom server](#using-an-alternative-to-the-build-step-custom-server)\n\n<p align=\"center\">\n    <img src=\"images/translation-prerendered.gif\" alt=\"Translations in prerendered pages\" />\n</p>\n\n## 1. About next-translate\n\nNext-translate is a tool to translate Next.js pages.\n\nThe main goal of this library is to keep the translations as simple as possible in a Next.js environment.\n\nThis library is very tiny and tree shakable.\n\n<p align=\"center\">\n    <img width=\"500\" src=\"images/bundle-size.png\" alt=\"Bundle size\" />\n</p>\n\n### How is this lib handling the routes?\n\nInstead of working on `/pages` directory to write our pages, we are going to generate this folder before building the app, and each page will have all the necessary translations from the locale.\n\nImagine that we are working in an alternative `/pages_` to build our pages:\n\n**/pages\\_**\n\n```bash\n.\n├── about.js\n├── index.js\n└── nested\n    └── index.js\n```\n\nThen, when we build the app, this **/pages** structure is going to be automatically generated:\n\n```bash\n.\n├── about.js\n├── ca\n│   ├── about.js\n│   ├── index.js\n│   └── nested\n│       └── index.js\n├── en\n│   ├── [...path].js\n├── es\n│   ├── about.js\n│   ├── index.js\n│   └── nested\n│       └── index.js\n├── index.js\n└── nested\n    └── index.js\n```\n\n**Note**: `/en/[...path].js` is a redirect from `/en/some-route` to `/some-route`\n\nEach page and its components can consume the translations with the `useTranslation` hook.\n\n```js\nconst { t, lang } = useTranslation()\nconst title = t('common:title')\n```\n\n## 2. Getting started\n\nThis is the recommended way to get started. However, if you don't like the \"build step\" you can use an [alternative](#12-do-i-need-this-build-step-is-there-an-alternative).\n\n### Install\n\n- `yarn add next-translate`\n\n**Note**: For a Next.js version below than `9.3.0`, use `next-translate@0.9.0` or below\n\nIn your **package.json**:\n\n```json\n\"scripts\": {\n  \"dev\": \"next-translate && next dev\",\n  \"build\": \"next-translate && next build\",\n  \"start\": \"next start\"\n}\n```\n\n### Use translations in your pages\n\nYou should create your namespaces files inside `/locales`. [See how to do it](#3-translation-jsons-folder)\n\nAdd a configuration file `i18n.json` in the root of the project. Each page should have its namespaces. Take a look to the [config](#4-configuration) section for more details.\n\n```json\n{\n  \"allLanguages\": [\"en\", \"ca\", \"es\"],\n  \"defaultLanguage\": \"en\",\n  \"currentPagesDir\": \"pages_\",\n  \"finalPagesDir\": \"pages\",\n  \"localesPath\": \"locales\",\n  \"pages\": {\n    \"*\": [\"common\"],\n    \"/\": [\"home\", \"example\"],\n    \"/about\": [\"about\"]\n  }\n}\n```\n\nThen, use the translations in the page and its components:\n\n```jsx\nimport useTranslation from 'next-translate/useTranslation'\n// ...\nconst { t, lang } = useTranslation()\nconst example = t('common:variable-example', { count: 42 })\n// ...\nreturn <div>{example}</div>\n```\n\n⚠️ **Important**: \\_app.js, \\_document.js and \\_error.js are not going to be wrapped with the translations context, so it's not possible to direclty translate these files. In order to do that, you should take a look at [DynamicNamespaces](#dynamicnamespaces) to load the namespaces dynamically.\n\n### Add /pages to .gitignore\n\n`/pages` directory is going to be generated every time based on `/pages_`, so it's not necessary to track it in git.\n\n## 3. Translation JSONs folder\n\nThe **/locales** directory should be like this:\n\n**/locales**\n\n```bash\n.\n├── ca\n│   ├── common.json\n│   └── home.json\n├── en\n│   ├── common.json\n│   └── home.json\n└── es\n    ├── common.json\n    └── home.json\n```\n\nEach filename matches the namespace, while each file content should be similar to this:\n\n```json\n{\n  \"title\": \"Hello world\",\n  \"variable-example\": \"Using a variable {{count}}\"\n}\n```\n\nIn order to use each translation in the project, use the _translation id_ composed by `namespace:key`(ex: `common:variable-example`).\n\n## 4. Configuration\n\n| Option                  | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            | Type                            | Default                                                                    |\n| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------- | -------------------------------------------------------------------------- |\n| `defaultLanguage`       | ISO of the default locale (\"en\" as default).                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           | `string|function`               | `\"en\"`                                                                     |\n| `allLanguages`          | An array with all the languages to use in the project.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 | `Array<string>`                 | `[]`                                                                       |\n| `ignoreRoutes`          | An array with all the routes to ignore in the middleware. This config property only effects using the `i18nMiddleware`, SO MAYBE YOU'LL NEVER NEED THIS.                                                                                                                                                                                                                                                                                                                                                                                                                                               | `Array<string>`                 | `['/_next/', '/static/', '/favicon.ico', '/manifest.json', '/robots.txt']` |\n| `redirectToDefaultLang` | When it's set to `true`, the route `/some-page` redirects to `/en/some-path` (if `en` is the default language). When it's set to `false`, entering to `/some-path` renders the page with the default language and the route `/en/some-path` redirects to `/some-page`.                                                                                                                                                                                                                                                                                                                                 | `boolean`                       | `false`                                                                    |\n| `currentPagesDir`       | A string with the directory where you have the pages code. This is needed for the \"build step\".                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        | `string`                        | `\"pages_\"`                                                                 |\n| `finalPagesDir`         | A string with the directory that is going to be used to build the pages. Only \"pages\" and \"src/pages\" are possible. This is needed for the \"build step\".                                                                                                                                                                                                                                                                                                                                                                                                                                               | `string`                        | `\"pages\"`                                                                  |\n| `localesPath`           | A string with the directory of JSONs locales. This is needed for the \"build step\".                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     | `string`                        | `\"locales\"`                                                                |\n| `loadLocaleFrom`        | As an alternative to `localesPath`, if `i18nMiddleware` is used instead of the \"build step\". It's an async function that returns the dynamic import of each locale. [See an example](/docs/USING_CUSTOM_SERVER.md#3-add-the-i18n-middleware)                                                                                                                                                                                                                                                                                                                                                           | `Function`                      | `null`                                                                     |\n| `pages`                 | An object that defines the namespaces used in each page. Example of object: `{\"/\": [\"home\", \"example\"]}`. To add namespaces to all pages you should use the key `\"*\"`, ex: `{\"*\": [\"common\"]}`. It's also possible to use regex using `rgx:` on front: `{\"rgx:/form$\": [\"form\"]}`. In case of using a custom server as an [alternative](#using-an-alternative-of-the-build-step-custom-server) of the \"build step\", you can also use a function instead of an array, to provide some namespaces depending on some rules, ex: `{ \"/\": ({ req, query }) => query.type === 'example' ? ['example'] : []}` | `Object<Array<string>/Function` | `{}`                                                                       |\n| `logBuild`              | Configure if the build result should be logged to the console                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          | `Boolean`                       | `true`                                                                     |\n\n## 5. API\n\n### useTranslation\n\n📦**Size**: ~614b\n\nThis hook is the recommended way to use translations in your pages / components.\n\n- **Input**: void\n- **Output**: Object { t: Function, lang: string }\n\nExample:\n\n```jsx\nimport React from 'react'\nimport useTranslation from 'next-translate/useTranslation'\n\nexport default function Description() {\n  const { t, lang } = useTranslation()\n  const title = t('common:title')\n  const description = t`common:description` // also works as template string\n  const example = t('common:example', { count: 3 }) // and with query params\n\n  return (\n    <>\n      <h1>{title}</h1>\n      <p>{description}</p>\n      <p>{example}</p>\n    <>\n  )\n}\n```\n\nThe `t` function:\n\n- **Input**:\n  - i18nKey: string (namespace:key)\n  - query: Object (example: { name: 'Leonard' })\n- **Output**: string\n\n### withTranslation\n\n📦**Size**: ~759b\n\nIt's an alternative to `useTranslation` hook, but in a HOC for these components that are no-functional.\n\nThe `withTranslation` HOC returns a Component with an extra prop named `i18n` (Object { t: Function, lang: string }).\n\nExample:\n\n```jsx\nimport React from 'react'\nimport withTranslation from 'next-translate/withTranslation'\n\nclass Description extends React.Component {\n  render() {\n    const { t, lang } = this.props.i18n\n    const description = t('common:description')\n\n    return <p>{description}</p>\n  }\n}\n\nexport default withTranslation(NoFunctionalComponent)\n```\n\n### Trans Component\n\n📦**Size**: ~1.5kb\n\nSometimes we need to do some translations with HTML inside the text (bolds, links, etc), the `Trans` component is exactly what you need for this. We recommend to use this component only in this case, for other cases we highly recommend the usage of `useTranslation` hook instead.\n\nExample:\n\n```jsx\n// The defined dictionary enter is like:\n// \"example\": \"<0>The number is <1>{{count}}</1></0>\",\n<Trans\n  i18nKey=\"common:example\"\n  components={[<Component />, <b className=\"red\" />]}\n  values={{ count: 42 }}\n/>\n```\n\n- **Props**:\n  - `i18nKey` - string - key of i18n entry (namespace:key)\n  - `components` - Array<Node> - Each index corresponds to the defined tag `<0>`/`<1>`.\n  - `values` - Object - query params\n\n### appWithI18n\n\n📦**Size**: ~4.7kb\n\nUsing the \"build step\" you'll never need this.\n\nThis HOC is the way to wrap all your app under translations in the case that you are using a custom server as an [alternative](#12-do-i-need-this-build-step-is-there-an-alternative) to the \"build step\", adding logic to the `getInitialProps` to download the necessary namespaces in order to use it in your pages.\n\nExample:\n\n`_app.js`\n\n```jsx\nimport appWithI18n from 'next-translate/appWithI18n'\nimport i18nConfig from '../i18n'\n\nfunction MyApp({ Component, pageProps }) {\n  return <Component {...pageProps} />\n}\n\nexport default appWithI18n(MyApp, i18nConfig)\n```\n\nSee more details about the [config](#4-configuration) you can use.\n\n### DynamicNamespaces\n\n📦**Size**: ~4.1kb\n\nThe `DynamicNamespaces` component is useful to load dynamic namespaces, for example, in modals.\n\nExample:\n\n```jsx\nimport React from 'react'\nimport Trans from 'next-translate/Trans'\nimport DynamicNamespaces from 'next-translate/DynamicNamespaces'\n\nexport default function ExampleWithDynamicNamespace() {\n  return (\n    <DynamicNamespaces\n      dynamic={(lang, ns) =>\n        import(`../../locales/${lang}/${ns}.json`).then((m) => m.default)\n      }\n      namespaces={['dynamic']}\n      fallback=\"Loading...\"\n    >\n      {/* ALSO IS POSSIBLE TO USE NAMESPACES FROM THE PAGE */}\n      <h1>\n        <Trans i18nKey=\"common:title\" />\n      </h1>\n\n      {/* USING DYNAMIC NAMESPACE */}\n      <Trans i18nKey=\"dynamic:example-of-dynamic-translation\" />\n    </DynamicNamespaces>\n  )\n}\n```\n\nRemember that `['dynamic']` namespace should **not** be listed on `pages` configuration:\n\n```js\n pages: {\n    '/my-page': ['common'], // only common namespace\n  }\n```\n\n### I18nProvider\n\n📦**Size**: ~1.8kb\n\nThe `I18nProvider` is a context provider internally used by next-translate to provide the current **lang** and the page **namespaces**. SO MAYBE YOU'LL NEVER NEED THIS.\n\nHowever, it's exposed to the API because it can be useful in some cases. For example, to use multi-language translations in a page.\n\nThe `I18nProvider` is accumulating the namespaces, so you can rename the new ones in order to keep the old ones.\n\n```jsx\nimport React from 'react'\nimport I18nProvider from 'next-translate/I18nProvider'\nimport useTranslation from 'next-translate/useTranslation'\n\n// Import English common.json\nimport commonEN from '../../locales/en/common.json'\n\nfunction PageContent() {\n  const { t, lang } = useTranslation()\n\n  console.log(lang) // -> current language\n\n  return (\n    <div>\n      <p>{t('common:example') /* Current language */}</p>\n      <p>{t('commonEN:example') /* Force English */}</p>\n    </div>\n  )\n}\n\nexport default function Page() {\n  const { lang } = useTranslation()\n\n  return (\n    <I18nProvider lang={lang} namespaces={{ commonEN }}>\n      <PageContent />\n    </I18nProvider>\n  )\n}\n```\n\n### i18nMiddleware\n\n📦**Size**: ~1.4kb\n\nIf you are using Automatic Static Optimization, you don't need this. This middleware is an alternative to the \"build step\".\n\n```js\nconst i18nMiddleware = require('next-translate/i18nMiddleware').default\nconst i18nConfig = require('./i18n')\n\n// ...\nserver.use(i18nMiddleware(i18nConfig))\n```\n\nSee more details about the [config](#4-configuration) you can use.\n\n**Props**:\n\n- `dynamic` - Function - Generic dynamic import of all namespaces (mandatory).\n- `namespaces` - Array<string> - List of namespaces to load dynamically (mandatory).\n- `fallback` - Any - Fallback to render meanwhile namespaces are loading (default: `null`)\n\n### Link\n\n📦**Size**: ~11kb (`next/link` size included)\n\nIt's a wrapper of `next/link` that adds the current language at the beginning of the path, so you don't have to worry to add the language in every navigation. In order to change the language, you can pass the `lang` as props:\n\n```jsx\nimport Link from 'next-translate/Link'\n\n// If the current language is 'en':\n\n// -> Navigate to /en/some-path\n<Link href=\"/some-path\"><a>Navigate</a></Link>\n\n // -> Navigate to /es/route-in-spanish\n<Link href=\"/route-in-spanish\" lang=\"es\"><a>Navigate</a></Link>\n\n// -> Navigate to /some-path\n<Link noLang href=\"/some-path\"><a>Navigate</a></Link>\n```\n\n**Props**: Same props than `next/link` + only one additional prop:\n\n- `lang`: `<String>` prop useful to navigate to a different language than the current one. The default value, if this prop is not provided, is the current language. So you don't need to worry about passing this prop for normal navigation.\n- `noLang`: `<Boolean>` prop to disable appending the current language to the route.\n\n### Router\n\n📦**Size**: ~10kb (`next/router` size included)\n\nIt's a wrapper of `next/router` so you can use the normal router of next.js, adding two extra methods:\n\n- **Router.pushI18n**: It is exactly the same as `Router.push`, except that it adds the current language at the beginning of the URL. In order to change the language, you can pass the `lang` into the `options`.\n- **Router.replaceI18n**: It is exactly the same as `Router.replace`, with the difference that it adds the current language at the beginning of the URL. In order to change the language, you can pass the `lang` into the `options`.\n\n```js\nimport Router from 'next-translate/Router'\n\n// If the current language is 'en':\n\n// -> Navigate to /en/some-path\nRouter.pushI18n('/some-path')\n\n// -> Navigate to /es/route-in-spanish\nRouter.pushI18n({ url: '/route-in-spanish', options: { lang: 'es' } })\n// or\nRouter.pushI18n('/route-in-spanish', undefined, { lang: 'es' })\n```\n\n### clientSideLang\n\n📦**Size**: ~590b\n\nUseful to get the language outside Components.\n\n```js\nimport clientSideLang from 'next-translate/clientSideLang'\n\n// ...\n\nexport function myClientSideHelper() {\n  const lang = clientSideLang()\n  // ...\n}\n```\n\nIt is **not recommended** to use the `clientSideLang` directly on the server-side because it's stored in a global variable and it can cause some concurrency issues.\n\n## 6. Plurals\n\nYou can define plurals this way:\n\n```json\n{\n  \"plural-example\": \"This is singular because the value is {{count}}\",\n  \"plural-example_0\": \"Is zero because the value is {{count}}\",\n  \"plural-example_2\": \"Is two because the value is {{count}}\",\n  \"plural-example_plural\": \"Is in plural because the value is {{count}}\"\n}\n```\n\nExample:\n\n```jsx\nfunction PluralExample() {\n  const [count, setCount] = useState(0)\n  const { t } = useTranslation()\n\n  useEffect(() => {\n    const interval = setInterval(() => {\n      setCount((v) => (v === 5 ? 0 : v + 1))\n    }, 1000)\n\n    return () => clearInterval(interval)\n  }, [])\n\n  return <p>{t('namespace:plural-example', { count })}</p>\n}\n```\n\nResult:\n\n![plural](images/plural.gif 'Plural example')\n\n**Note**: Only works if the name of the variable is {{count}}.\n\n## 7. Use HTML inside the translation\n\nYou can define HTML inside the translation this way:\n\n```json\n{\n  \"example-with-html\": \"<0>This is an example <1>using HTML</1> inside the translation</0>\"\n}\n```\n\nExample:\n\n```jsx\nimport Trans from 'next-translate/Trans'\n// ...\nconst Component = (props) => <p {...props} />\n// ...\n<Trans\n  i18nKey=\"namespace:example-with-html\"\n  components={[<Component />, <b className=\"red\" />]}\n/>\n```\n\nRendered result:\n\n```html\n<p>This is an example <b class=\"red\">using HTML</b> inside the translation</p>\n```\n\nEach index of `components` array corresponds with `<index></index>` of the definition.\n\nIn the `components` array, it's not necessary to pass the children of each element. Children will be calculated.\n\n## 8. Nested translations\n\nIn the namespace, it's possible to define nested keys like this:\n\n```json\n{\n  \"nested-example\": {\n    \"very-nested\": {\n      \"nested\": \"Nested example!\"\n    }\n  }\n}\n```\n\nIn order to use it, you should use \".\" as id separator:\n\n```js\nt`namespace:nested-example.very-nested.nested`\n```\n\n## 9. How to change the language\n\nIn order to change the current language you don't need anything of this library, you can do it directly with the next navigation:\n\n- https://nextjs.org/learn/basics/navigate-between-pages\n\nThe only thing to remember is to navigate with the **/lang/** on front.\n\nAn example of a possible `ChangeLanguage` component:\n\n```js\nimport React from 'react'\nimport Link from 'next-translate/Link'\nimport useTranslation from 'next-translate/useTranslation'\nimport i18nConfig from '../i18n.json'\n\nconst { allLanguages } = i18nConfig\n\nfunction ChangeLanguage() {\n  const { t, lang } = useTranslation()\n\n  return allLanguages.map((lng) => {\n    if (lng === lang) return null\n\n    // Or you can attach the current pathame at the end\n    // to keep the same page\n    return (\n      <Link href=\"/\" lang={lng} key={lng}>\n        {t(`layout:language-name-${lng}`)}\n      </Link>\n    )\n  })\n}\n```\n\n## 10. Get language in the special Next.js functions\n\nIf you are using an alternative to the \"build step\", this section is not applicable.\nIn order to use the `lang` in the special Next.js functions, the `lang` property is added to the context.\n\n### getStaticProps\n\n```js\nexport async function getStaticProps({ lang }) {\n  return {\n    props: {\n      data: fetchMyDataFromLang(lang),\n    },\n  }\n}\n```\n\nSee [here](https://nextjs.org/docs/basic-features/data-fetching#getstaticprops-static-generation) the official Next.js docs about `getStaticProps`.\n\n### getStaticPaths\n\n```js\nexport async function getStaticPaths({ lang }) {\n  return {\n    paths: generatePathsFromLang(lang),\n    fallback: false,\n  }\n}\n```\n\nSee [here](https://nextjs.org/docs/basic-features/data-fetching#getstaticpaths-static-generation) the official Next.js docs about `getStaticPaths`.\n\n### getServerSideProps\n\n```js\nexport async function getServerSideProps({ lang }) {\n  return {\n    props: {\n      data: queryDataFromDB(lang),\n    },\n  }\n}\n```\n\nSee [here](https://nextjs.org/docs/basic-features/data-fetching#getserversideprops-server-side-rendering) the official Next.js docs about `getServerSideProps`\n\n### getInitialProps\n\nRecommended: Use **getStaticProps** or **getServerSideProps** instead.\n\n```js\nMyPage.getInitialProps = async ({ lang }) => {\n  return {\n    data: fetchMyDataFromLang(lang),\n  }\n}\n```\n\nSee [here](https://nextjs.org/docs/api-reference/data-fetching/getInitialProps#getinitialprops-for-older-versions-of-nextjs) the official Next.js docs about `getInitialProps`\n\n## 11. How to use multi-language in a page\n\nIn some cases, when the page is in the current language, you may want to do some exceptions displaying some text in another language.\n\nIn this case, you can achive this by using the `I18nProvider`.\n\nLearn how to do it [here](#i18nprovider).\n\n## 12. Do I need this \"build step\"? Is there an alternative?\n\nThe \"build step\" exists only to simplify work with Automatic Static Optimization, so right now it is the recommended way. However, if you prefer not to do the \"build step\", there are two alternatives.\n\n### First alternative\n\nYou can achive the same with dynamic routes.\n\nPros and cons:\n\n- 🟢 Automatic Static Optimization\n- 🔴 Hard to configure\n\nSee a full example [here](https://github.com/vinissimus/next-translate/tree/master/examples/with-dynamic-routes)\n\nIn future major releases, we may evolve simplifying this and removing the \"build step\". If you want to help on this, there is an open issue [here](https://github.com/vinissimus/next-translate/issues/129) to discuss.\n\n### Second alternative\n\nIf you don't need Automatic Static Optimization in your project, you can achive the same by using a custom server.\n\nPros and cons:\n\n- 🔴 Automatic Static Optimization is not an option\n- 🟢 Easy to configure\n\nLearn more: [Docs](docs/USING_CUSTOM_SERVER.md) · [Example](https://github.com/vinissimus/next-translate/tree/master/examples/with-server)\n\n## 13. Demos\n\n### Using the \"build step\"\n\n- `yarn install`\n- `yarn example:static-site`\n\n### Using an alternative to the build step: dynamic routes\n\n- `yarn install`\n- `yarn example:with-dynamic-routes`\n\n### Using an alternative to the build step: custom server\n\n- `yarn install`\n- `yarn example:with-server`\n\n[badge-prwelcome]: https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square\n[prwelcome]: http://makeapullrequest.com\n[spectrum]: https://spectrum.chat/next-translate\n\n## Contributors ✨\n\nThanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/emoji-key)):\n\n<!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->\n<!-- prettier-ignore-start -->\n<!-- markdownlint-disable -->\n<table>\n  <tr>\n    <td align=\"center\"><a href=\"https://aralroca.com\"><img src=\"https://avatars3.githubusercontent.com/u/13313058?v=4\" width=\"100px;\" alt=\"\"/><br /><sub><b>Aral Roca Gomez</b></sub></a><br /><a href=\"#maintenance-aralroca\" title=\"Maintenance\">🚧</a> <a href=\"https://github.com/vinissimus/next-translate/commits?author=aralroca\" title=\"Code\">💻</a></td>\n    <td align=\"center\"><a href=\"https://twitter.com/vincentducorps\"><img src=\"https://avatars0.githubusercontent.com/u/6338609?v=4\" width=\"100px;\" alt=\"\"/><br /><sub><b>Vincent Ducorps</b></sub></a><br /><a href=\"https://github.com/vinissimus/next-translate/commits?author=vincentducorps\" title=\"Code\">💻</a></td>\n    <td align=\"center\"><a href=\"https://www.rahwn.com\"><img src=\"https://avatars3.githubusercontent.com/u/36173920?v=4\" width=\"100px;\" alt=\"\"/><br /><sub><b>Björn Rave</b></sub></a><br /><a href=\"https://github.com/vinissimus/next-translate/commits?author=BjoernRave\" title=\"Code\">💻</a></td>\n    <td align=\"center\"><a href=\"https://github.com/justincy\"><img src=\"https://avatars2.githubusercontent.com/u/1037458?v=4\" width=\"100px;\" alt=\"\"/><br /><sub><b>Justin</b></sub></a><br /><a href=\"https://github.com/vinissimus/next-translate/commits?author=justincy\" title=\"Code\">💻</a></td>\n    <td align=\"center\"><a href=\"https://github.com/psanlorenzo\"><img src=\"https://avatars2.githubusercontent.com/u/42739235?v=4\" width=\"100px;\" alt=\"\"/><br /><sub><b>Pol</b></sub></a><br /><a href=\"#infra-psanlorenzo\" title=\"Infrastructure (Hosting, Build-Tools, etc)\">🚇</a></td>\n    <td align=\"center\"><a href=\"https://twitter.com/ftonato\"><img src=\"https://avatars2.githubusercontent.com/u/5417662?v=4\" width=\"100px;\" alt=\"\"/><br /><sub><b>Ademílson F. Tonato</b></sub></a><br /><a href=\"https://github.com/vinissimus/next-translate/commits?author=ftonato\" title=\"Code\">💻</a></td>\n  </tr>\n</table>\n\n<!-- markdownlint-enable -->\n<!-- prettier-ignore-end -->\n\n<!-- ALL-CONTRIBUTORS-LIST:END -->\n\nThis project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind welcome!\n","readmeFilename":"README.md"}