Coder Social home page Coder Social logo

react-i18next-gitbook's Introduction

Introduction

What is react-i18next?

react-i18next is a powerful internationalization framework for React / React Native which is based on i18next. Check out the history of i18next and when react-i18next was introduced.

{% hint style="info" %} You should read the i18next documentation. The configuration options and translation functionalities like plurals, formatting, interpolation, ... are documented there. {% endhint %}

The module provides multiple components eg. to assert that needed translations get loaded or that your content gets rendered when the language changes.

{% embed url="https://www.youtube.com/watch?t=705s&v=SA_9i4TtxLQ" %}

react-i18next is optimally suited for server-side rendering. It provides extra extension point to work with next.js, for e.g. Learn more.

As react-i18next depends on i18next you can use it in any other UI framework and on the server-side (node.js, .net, ...) too. Like the React philosophy - just:

Learn once - translate everywhere.

{% hint style="success" %} Here you'll find a simple tutorial on how to best use react-i18next.
Some basics of i18next and some cool possibilities on how to optimize your localization workflow.
{% endhint %}

{% hint style="info" %} Using Next.js?
Here you'll find a blog post on how to best use next-i18next with client side translation download and SEO optimization.



Using Next.js 13 with the new app directory?
Then this article is what you are looking for!

{% endhint %}

{% hint style="info" %} Using Remix?
Here you'll find a simple example and here a step by step tutorial on how to best use remix-i18next.

{% endhint %}

{% hint style="info" %} Using Gatsby?
Here you can find an example and an appropriate blog post.

{% endhint %}

What does my code look like

Before: Your React code would have looked something like:

...
<div>Just simple content</div>
<div>
  Hello <strong title="this is your name">{name}</strong>, you have {count} unread message(s). <Link to="/msgs">Go to messages</Link>.
</div>
...

After: With the Trans component just change it to:

...
<div>{t('simpleContent')}</div>
<Trans i18nKey="userMessagesUnread" count={count}>
  Hello <strong title={t('nameTitle')}>{{name}}</strong>, you have {{count}} unread message(s). <Link to="/msgs">Go to messages</Link>.
</Trans>
...

If you prefer not using semantic keys but text - that's also possible.

i18next supports translation management tools such as locize.com.

{% hint style="success" %} Here you can find a step by step guide, which will unleash the full power of i18next in combination with locize.
See how your developer experience with this localization workflow could look like.
There's also the possibility to have an even more focused developer experience, with the help of the auto-machinetranslation workflow and the use of the save missing keys functionality, new keys not only gets added to locize automatically, while developing the app, but are also automatically translated into the target languages using machine translation (like Google Translate). {% endhint %}

{% embed url="https://www.youtube.com/watch?v=TFV_vhJs5DY" %}

Learn more about the enterprise offering

react-i18next-gitbook's People

Contributors

adrai avatar atomicpages avatar echelonka avatar emmasimon avatar ewalti avatar ezuk avatar fishmandev avatar gitbook-bot avatar gnusiva avatar igorsantos07 avatar itherael avatar jamuhl avatar kokushkin avatar mareksuscak avatar mareoraft avatar mattwr18 avatar mhienle avatar modulitos avatar ncoen97 avatar nicgirault avatar odiumediae avatar pborreli avatar pedrodurek avatar ryansonshine avatar spencerhutch avatar stopa avatar tanvibhakta avatar theapplefreak avatar wilk avatar xd3coder avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

react-i18next-gitbook's Issues

Jest throws an error detecting Trans component. ReferenceError: renderNodes is not defined

1

Following this documentation: https://react.i18next.com/latest/trans-component

This is the piece of code I have written inside my component that works fine on browser.

<Trans i18nKey="myKey">
        Welcome to <br /> This Space
</Trans>

Not sure if this is relevant. But myKey looks something like this in JSON:

myKey: Welcome to <1 /> This Space

But due to that my test cases have started faling:

ReferenceError: renderNodes is not defined

  11 |      // this mock makes sure any components using the translate HoC receive the t function as a prop
  12 |      withTranslation: () => (Component) => (props) => <Component t={(k) => k} {...props} />,
> 13 |      Trans: ({ children }) => renderNodes(children),
     |                               ^
  14 |      Translation: ({ children }) => children((k) => k, { i18n: {} }),
  15 |      useTranslation: () => useMock,
  16 |

  at Trans (__mocks__/react-i18next.js:13:27)

If I remove the above snippet the test cases work fine.

withTranslation() HOC does not pass prop's down

I'm trying to pass down the props in a component wrapped with the withTranslation() HOC. Them problem is that this HOC does not pass down the props to the wrapped component.

class SpeedDialWrapper extends React.PureComponent<
  ISpeedDialWrapper,
  ISpeedDialState
> { ... }

export default withTranslation()(withStyles(styles as any, { withTheme: true })(
  SpeedDialWrapper
) as any);


// in another file

import SpeedDial from "../../../shared/components/speed-dial-wrapper.component";

class ScheduleSpeedDial extends React.PureComponent<
  ISpeedDialTheme,
  ISpeedDialState
> {
  public render() {
    return <SpeedDialWrapper actions={this.getActions()} />; // The withTranslation HOC interface does not accept any props
  }
}

I need to pass down the props for the wrapped component. How can I do that?

Getting started with escapeValue to false

Documentation issue

In the getting started guide in the basic sample, the options have an escapeValue to false.

Motivation

This part doesn't seem important for this sample (as there is no interpolation) and this can leads into security issues for beginning users which don't understand this parameter. If there is a reason I think a comment explaining why would be great or remove this part if not necessary.

(Ready to open a PR if you think it should be removed)

Make docs neutral and clean from "ads"

๐Ÿš€ Feature Proposal

I'm getting started with i18next and I found it a bit........ confusing....... that there's a couple of semi-related "ads" on the introduction page. Why there's a mention of the translation-check plugin right at the start? And then, the page ends with a long, camouflaged ad on Locize.

Not to mention the ad links at the header of the docs as well, intermixed with a link to the main i18next docs...

It's also interesting how there's a bunch of "check docs for this here" but when it comes to Locize, you do use SEO-friendly links, which might even seem sneaky at some spots.

Edit: I noticed later that the exact same suggestions happen at the i18next Extractor docs (also tangential, since for instance translation-check is not an extraction tool but an inspector). This repetition of specific tool suggestions makes it a bit smelly, even for an inattentive reader. It also shows in a lot of other spots (such as Intro, History, Comparison...). I'm mentioning it here so I don't repeat the issue across repos without further discussion, since I'm sure this is a sensitive topic.

Motivation

I understand this is how you monetize the development, but the way many parts of the docs are written feels weird, to put it kindly. That site is for docs on how to use it, we are not supposed to try to interpret if "this is useful for what I want" or "this is an ad for a related service". There are a couple of passages that might feel biased in the i18next docs too.

Besides that, why's a specific plugin (home-made, btw) suggested on the home page instead of any other plugin, for instance? Not to mention other services also link with i18next, but of course, Locize is the only one extensively mentioned (which kinda "makes sense", just doesn't seem fair, nor related).

Example

I would suggest making the docs actually neutral and focused, by removing plugin or service suggestions from unrelated pages - leave these to pages on plugins and pluggable services...

I hope this doesn't feel aggressive, but I really felt odd to see "internal ads" on multiple documentation pages while I'm trying to understand i18next's feature set, capabilities, and how it works. Not to mention they don't look like ads, since they're completely mixed with the actual content.

Suggestion fix for local translation files

Is recommended in documentation add files in (/public/locales/en/translation.json). But this is broken the application because this is not supported imports outside src

Module not found: You attempted to import ../public/locales/en/translation.json which falls outside of the project src/ directory. Relative imports outside of src/ are not supported.

I recommend the change simple in docs:
public => src
(/src/locales/en/translation.json)

https://react.i18next.com/legacy-v9/step-by-step-guide

document <Trans /> `link` reserved tag name

๐Ÿ› Bug Report

As documented in Alternative Usage, I've tried to used named tag for <Trans /> with the tag key link.

It doesn't work as expected, as it seems there are some reserved names for using react-i18next component.
I would expect the documentation to warn about this restriction.

To Reproduce

<Trans
  i18nKey="goToMeeting"
  components={{
    link: <Link to={`/${orgId}/meetings`} />,
  }}
 />
{
  "goToMeeting": "Open <link>meetings</link>
}
<!-- result -->
Open <link />meetings

But if I use another tag name, like a, it does work :

<Trans
  i18nKey="goToMeeting"
  components={{
     a: <Link to={`/${orgId}/meetings`} />,
   }}
 />
{
  "goToMeeting": "Open <a>meetings</a>
}
<!-- result -->
Open <a href="/1/meetings">meetings</a>

Expected behavior

<Trans
  i18nKey="goToMeeting"
  components={{
     link: <Link to={`/${orgId}/meetings`} />,
   }}
 />
{
  "goToMeeting": "Open <link>meetings</link>
}
<!-- result -->
Open <a href="/1/meetings">meetings</a>

Your Environment

  • runtime version: Chrome 85
  • i18next version: 19.6.3
  • react-i18next: 11.7.0
  • os: Mac

Thanks for this awesome component!

ready state is undefined until translations are loaded

Documentation issue

The documentation for the useTranslation hook notes, to check for ready === false but the ready state is undefined until the translations are loaded. So it should be checked if ready !== true instead.

TypeError: cannot read property 'use' of undefined: i18n.use(initReacti18next).init line of i18n.js

I've encountered problems difficulty upgrading our React-Typescript project from using i18next v17.1.0 and react-i18next 10.13.1 to current versions (i18next v17.3.1 & react-i18next v10.13.2).
Everything worked before with the older versions, but I can't seem to get rid of type error occurring in my i18n.ts file.

The error is: "Uncaught TypeError: i18n.use is not a function at Object../src/app/i18n.ts (i18n.ts:9)"

Depending on how I import i18next into my i18n.ts file, either:

  1. the web app fails in the browser with this Type Error, but my jest/enzyme integration tests pass,
    OR
  2. the web app works fine (no error) but all my jest/enzyme tests fail with the aforementioned type error.

Things I've tried:

  1. If I do the following in my i18n.js, then the tests pass but the web app fails in the browser:
import * as i18n from 'i18next';
  1. If I do this instead, then the web app works, but tests fail:
import i18n from 'i18next';
  1. If I do this (which I saw suggested in this thread), it fails in the browser but tests pass:
import * as i18nextDefault from 'i18next'
const i18n: typeof i18nextDefault = require('i18next');
  1. Setting tconfig's 'esModuleInterop' to TRUE works: the web app works AND the tests all pass, but unfortunately I cannot use this project-wide setting because it causes dozens of other libraries used by our project to fail.

I have a sample repo that reproduces the problem here:

Please see the minimal sample repo at https://github.com/sraisty1c/test-i18next
You can look at the last 3 or 4 commits and see what I mean.


I'm sure this is some kind of user error, since I am pretty new to Typescript, React, and Javascript. But I've been researching this for a day or two now, and feel like I'm at a dead end. I sincerely appreciate your help.

And I thank you for putting out such a useful package. It has worked well for us for the last 8 months, which is why I want to figure out this problem so we can keep using it.

Thank you in advance for your help.

On navigate() show child route shows 404 not found

Hello I have one issue, Please help

I have used this "gatsby-plugin-react-i18next" for language translation.

My project contains One parent route /home and have one child route /home/detail/:id. In order to go to the child route I have used navigate(/home/detail/${post.id}/}) this from import { useI18next } from "gatsby-plugin-react-i18next" but on child route it says "Page Not Found"

To check code you can find here https://github.com/sanju-developer/Gatsby-demo-with-materialUI/tree/lang-trans in lang-trans branch.

Thanks in advance :)

Trans component docs incorrectly say it is does not rerender on language change.

Documentation issue

It does ONLY interpolation. It does not rerender on language change or load any translations needed. Check useTranslation hook or withTranslation HOC for those cases.

from

It does ONLY interpolation. It does not rerender on language change or load any translations needed. Check [`useTranslation` hook](usetranslation-hook.md) or [`withTranslation` HOC](withtranslation-hoc.md) for those cases.

This does not seem to be true at all. I am able to use <Trans> and have it rerender correctly when my selected language changes.

Motivation

Docs for Trans component seem to be wrong.

Document reportNS prop

I've just spent more than a day looking for a solution to pass down the necessary namespaces to the client in order to initially render a page, until I've finally found this little gem hidden in I18nextProvider's code ;-)

Not translating in IE11

It looks like translation isn't happening in IE11. I set the language in to Portuguese-Brazil and the language is still English in IE11.

I am attaching a couple of screen shots.
Screen Shot 2019-08-22 at 11 59 45 AM
Screen Shot 2019-08-22 at 12 00 03 PM

React Hook "useTranslation" is called in function

I am trying to use i18next inside a form model to store a mobx-state-tree

My model form code has this structure...


import { types, flow, getRoot } from 'mobx-state-tree'

import {useTranslation} from 'react-i18next';

export const MyFormModel = types
.model('Form',{..})
.views(...)
.actions(self => ({
validate(){
//trying to use it here but makes the problem...
const {t} = useTranslation();
const msg = t('WRONG_NAME');
self.errors.set('userName', msg)
.
.
.
}))
type MyFormModelType = typeof MyFormModel.Type
export interface MyForm extends MyFormModelType {}


I am confident my i18next configuration is correct because I am using i18next successfully in the rest of my app when using it in class or functional react components but, for this kind of form stores for mobx I am getting this error:
"React Hook "useTranslation" is called in function "validate" which is neither a React function component or a custom React Hook function react-hooks/rules-of-hooks"

I just can't find the way to solve this. Any ideas or suggestions you can give me to solve this?

Testing with typescript

In the testing doc (https://react.i18next.com/misc/testing) it says to export the component that is not wrapped with withNamespaces. However, when using typescript the base component must be provided all the props coming from withNamespaces. This is quite heavy to provide. Do you have any suggestion to deal with Typescript in tests?

Documentation is difficult to read

Hi! Thanks for the great package!

I'm trying to understand how to correctly use and fully configure this package.

I see configuration options scattered here and there. The text throughout the documentation is mostly trying to sell me the use of the package. That's fine. Ok, let's say I'm on board. What next?

https://react.i18next.com/getting-started

Install using npm

$ npm install react-i18next --save
These are different installation instructions than on the other page.
It would also be good to have "Install using yarn" section.

yarn is only randomly mentioned here:
https://github.com/i18next/react-i18next-gitbook/blob/db2ad5eb49604063514b7c6a5c0981d6814cc274/misc/using-with-icu-format.md

Here's different install instructions page:
https://react.i18next.com/guides/quick-start

Install both react-i18next and i18next package:
npm install react-i18next i18next --save
(notice also no $ sign before, it's a small issue, but ideally, it would look the same)

What's the difference between "Getting started" and "Quick start" page? What's the purpose of having two pages?

"Quick start" page is the closest to what I was looking for when I came in search for i18n package to use in my react app.

Let's see some more examples:

Load from CDN

There's no actual <script> tag in here. Just a direct link to javascript file. (Too bad unpkg doesn't have search feature like https://cdnjs.com/)

Drawbacks of other i18n solutions

https://react.i18next.com/guides/the-drawbacks-of-other-i18n-solutions

Let's make the sample using our own base i18n framework i18next. Like all other solutions, some come drawbacks.

Before we come to the drawbacks let's highlight some advantage of those solutions above - they are very simple to get started.

With loading translations asynchronous there comes another problem - does your framework handle the pending state during loading translation?

In most frameworks you will end having to split this into multiple translation strings. But for your translators it would make sense to have this as one sentence to translate like eg.:

In the /dist folder you find specific builds for commonjs, es6 modules,...

There are links in the README.md that are broken: https://github.com/i18next/react-i18next#v9

It's off-putting to have a package specified in language and grammar, have grammatical/spelling errors. Especially if you're offering translation services (which I'll most probably use! Thanks!). ...but please fix these.

Is there a single page where I can see all the configuration options for i18n package? Same for react-i18n package?

I understand there has been a lot of work put into this project. And I appreciate it. My feedback above is in hope to make it even better and to remove these little nuances to make this project truly shine. Because that's what these are, just little nuances that hide the full quality of the project. Thanks!

EDIT: I found the configuration options: ๐Ÿ’ช https://www.i18next.com/overview/configuration-options

EDIT 2: What's this wait: true option (i18next/react-i18next#219)? Where can I read more about it?

Add examples of nesting, formatters with Trans

Documentation issue

The Trans documentation is great!~ I'm hoping it can be improved by adding an example of nesting. And, an example of formatting.

Formatter? Not sure if this is right and cannot find any examples on Google:

<Trans>Today's date is {{ date, SOME_DATE_FORMATTER }}</Trans>

Nesting:

No idea how to do this, but to display "13 of 52" for example:
const count = 13;
const total = 52;
...
<Trans count={13}>{{count, INTEGER}} <strong>of</strong>{t('{{count, INTEGER}}', { count: total })}</Trans>

or something like that.

Motivation

Trans can be unintuitive to work with and adding these two examples (or whatever their working equivalents are) would greatly enhance the documentation. All the other nesting and formatter docs use the t function so the hole in the Trans documentation is quite daunting.

Link to github gitbook repository

Documentation issue

As i18next user and related gitbook reader, I would like to know where the documentation source code is.

Motivation

As i18next gitbook reader, when I encounter some broken links (ex here)I want to fix them.

I took many time to find related git repository.

It would be great to have a link to this repository.

It seems that gitbook badge is only ads to gitbook service and not to this repository.

useTranslation hook with Typescript issue

I'm currently using i18next v19.1.0 and react-i18next 11.3.1 with Typescript v3.7.2

When passing in a string key to the t function from useTranslation(), it keeps saying -

Expected 0 arguments, but got 1.

image

I feel like I might just be missing something basic. Any ideas?

Deep keys does not work

๐Ÿ› Bug Report

Trying to use deep keys does not work as expected. This is my ns

alerts: {
  type: {
     t1: "low",
     t2: "high"
  },
  msg: "alert message"
}

Using useTranslate('alerts'); I can print next block with no problem

t('msg')

But I can not print t1. I have tried next lines

t('type.t1');
t('type:t1');
t('alerts:type.t1');
t('alerts:type:t1');

And the only string that I receive is the same key I'm sending.

I have tried returnObjects: true option and it does return whole object but as far as I can tell we should be able to extract just an inner key of that object

To Reproduce

Here is a codeSandbox to check if t1 in test is displayed
A codesandbox

Expected behavior

A clear and concise description of what you expected to happen.

// Paste the expected results here

Your Environment

Trans component documentation unclear

Following what little context the trans component documentation gives, I cannot get any kind of functionality out of the Trans component other than explicitly rendering its children. There are no examples for how this is supposed to be used within a component (need more context than just showing what the Trans component JSX would look like); this doesn't even show how the Trans component-specific strings fit into your i18n initialization object, just shows a key and a value without any context. The "working example" does not illustrate how to connect your i18n configuration to the trans component, so it is entirely unclear how it even translates the paragraph (if it even does, I haven't tried cloning it and running it because I'd rather understand it first)

This seems like such a useful tool, but all of the documentation is incredibly hard to follow, and the examples that are linked out to are rarely illustrative. I lost my patience with this specific component, but the general theme of my complaints seem to be present throughout the documentation. To be useful to people who don't already understand the tool, the documentation should contain more context in the code samples. This feels more like I'm trying to solve a jigsaw puzzle than following any instructions.

https://react.i18next.com/components/trans-component

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.