You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesión a prueba de IA

Antes: $249

Currency
$209
Suscríbete

Termina en:

0 Días
3 Hrs
25 Min
3 Seg

Arquitectura de internacionalización para componentes en React

9/12
Resources

How can we handle internationalization in React and Next.js?

Internationalization becomes a crucial element in applications that seek to reach a global audience. Using JavaScript together with React and Next.js, we can deploy efficient solutions to translate interfaces into various languages. Let's present an approach that addresses this need in a simple and scalable way, divided by locale (locales) and components.

How to organize the JSON file structure?

To improve internationalization, it is essential to organize our JSON files in a logical way. We start with one giant JSON file with all our locales, but as we increase the number of locales and labels, this approach becomes less efficient. Thus, it is advisable to create multiple JSON files, organized as follows:

  1. Split by locale: Have a separate file for each locale (e.g. es.json for Spanish and en.json for English).
  2. Split by components: Within each locale, generate one JSON file per component. This is useful especially when different components require different translations.

This structure not only improves scalability, but also facilitates the work of teams of editors and copywriters, allowing to adjust the text to specific cultural requirements, even if this means having duplicate labels.

How to implement internationalization with React Context and Hooks?

React tools, such as Context and Hooks, are fundamental for handling internationalization. These allow you to efficiently share information across multiple components without excessive property passing.

Steps to implement:

  1. Context: we will create a context in React using React.createContext(). This will serve as a container for translations and will facilitate access throughout the application.

  2. Translation Hook: Implement a Hook, for example useTranslations, that connects to the context and extracts the necessary translations for each component. This way, the component will not have to worry about internationalization logic.

import { useContext } from 'react';import { TranslationContext } from './TranslationContext';
function useTranslations() { const { labels } = useContext(TranslationContext); return labels;}

What are the benefits and challenges of this approach?

Benefits:

  • Scalability: The per-component and local structure allows for orderly growth without overloading the application.
  • Reusability of logic: Thanks to React Context and Hooks, the internationalization logic remains centralized, clear and easy to reuse.

Challenges:

  • Duplicity of labels: In large applications, there could be duplication of texts, which although manageable, represents aspects that demand constant review in search of optimizations and simplification.

It is essential to consider all these strategies in a practical context, evaluating pros and cons. You can start by implementing your own solution or by using specialized libraries such as react-intl or react-i18next, which solve similar problems and offer additional functionality.

What other resources can help in the internationalization process?

Popular libraries offer robust tools to handle internationalization efficiently. By examining how these tools operate, we gain valuable insights that allow us to adapt their techniques to our specific needs.

Recommended libraries:

  • React Intl: Provides internationalization APIs for formatting numbers, dates, and strings in a localized manner.
  • React-i18next: Powerful translation library that provides full support for React Native and Next.js.

Internationalization is a continuous journey of optimization and adjustment as the audience and content evolves. Explore, experiment and find the best approach for your app.

Contributions 5

Questions 1

Sort by:

Want to see more contributions, questions and answers from the community?

Links a las documentaciones:

⚛ Arquitectura de internacionalización para componentes en React

Recursos

Overview | Format.JS

Introduction

Tutorial - Internationalization of React apps - LinguiJS documentation

https://github.com/lukeed/rosetta

Apuntes

“Analicemos la forma simple”

  • Vamos a tener un JSON donde estarán todos los locales
  • Estarán separadas por secciones de locales
// allLabels.json
{
	"es":{
		"buy": "Comprar",
		"accept": "Aceptar",
		...
	},
	"en-US":{
		"buy": "Buy",
		"accept": "Accept",
		...	
	},
	...
}

Para implementar esta solución mediante JavaScript se realizaría de la siguiente manera:

import allLabels from "locales/labels.json";

function getServerSideProps(){ ... }

function MyComponent ({locale}){
	const labels = allLabels[locale];
	return (
		<Button>{labels.comprar}</Button>
	)
}

Desventajas

  1. Entre más locales, más pesado el archivo. ¿Dividimos también por locales?
  2. Entre más labels, más pesado el archivo. ¿Divididimos por componentes?
  3. La responsabilidad está repetida en cada componente. ¿La extraemos?

Dividiendo por componentes

// locales/es/checkout.json
{
	"buy": "Comprar",
	"addToCart": "Agregar al carro",
	"contactUs": "¿Interesado/a?"
}

// locales/es/about.json
{
	"about": "Nosotros",
	"phone": "Teléfono",
	"contactUs": "Conócenos"
}

Desventajas

  1. Entre más locales, más pesado el archivo. ¿Dividimos también por locales?
  2. Entre más labels, más pesado el archivo. ¿Divididimos por componentes?
  3. La responsabilidad está repetida en cada componente. ¿La extraemos?

React

  1. React.Context: para abstraer lógica en un solo lugar y permitir su acceso a componentes que la necesiten sin prop drilling.
  2. React Hooks: para encapsular y reusar lógica.
import useTranslations from "useTranslations"

function getServerSideProps(){}

function MyComponent(){
	const labels = useTranslations()

	return (
		<Button>{labels("comprar")}</Button>
	)
}
  • El hook retorna los labels listos para ser usados
  • El componente en ningún momento piensa que locale utilizar, ya que todo está abstraído en el hook
function useTranslations(){
	const ctx = useContext(LocaleContext);
	const locale = ctx.getCurrentLocale();
	const labels = ctx.labels.get(locale);
	return labels;
}
  • Mediante esta solución estamos:
    1. Creando una solución escalable
    2. Utilizando todo el poder de React
    3. Con ayuda de Next.js podemos utilizar mediante Next.js

Librerías populares

  • react-intl
  • react-i18next
  • lingui
  • rosetta
  • next-intl

Increíble esta manera de enseñar mostrándonos como piensa y como soluciona un problema.

Excelente clase, me gusta mucho que te hace pensar en las diferentes soluciones que puedes crear con ejemplos claros, como lo puedes hacer tu mismo y las librerías que puedes usar.

next-i18next <-- Checken ese Repo. Facilita todo lo visto en esta clase!