A react translation library with optional routing
npm install k2-react-translate





!GitHub stars
!GitHub stars
!GitHub stars
A simple, easy-to-use translation library based on React's Context API, with optional localizedreact-router routing.
See demo on CodeSandbox.

- Problem Statement
- Setup
- Documentation (Translation)
- Documentation (Localized Routing)
- Development
- Known Issues
- Changelog
TBD
This ES5 module is distributed via npm and
should be installed as a production dependency.
Note: TypeScript syntax is used throughout the docs, but the library should run without issue on ababel/react setup.
Using _yarn_ (preferred)
```
yarn add -E k2-react-translate
or via _npm_
``
npm i -S -E k2-react-translate
- react@^16.8.0
- react@^16.8.0 would have to be installed to use the useTranslate hook.react-dom@^16.8.0
- react-router-dom
- history
-
Typescirpt type definitions come bundled in.
If using TypeScript in VS Code, add the following configuration to your tsconfig.json to allow for
importing json files into your modules:
`jsonc`
// tsconfig.json
{
"compilerOptions": {
// other config options ...
"resolveJsonModule": true
}
}
Setup your translations:
If using VS Code, the richie5um2's
Sort JSON objects
marketplace extension may help to keep your translations file organized.
`jsonc`
// translations.json
{
"HELLO": {
"en": "Hello",
"fr": "Bonjour"
},
"HELLO_NAME": {
"en": "Hello, {firstName}",
"fr": "Bonjour, {firstName}"
},
"AVAILABLE_IN_COUNTRY": {
"en": "Available in {countryName}",
"fr": "Disponsible en {countryName}"
},
"PRIVACY_POLICY": {
"en": "Privacy Policy",
"fr": "Politique de Confidentialité"
}
}
Entry point:
`tsx
// index.tsx
import * as React from 'react'; // standard TypeScript syntax
import * as ReactDOM from 'react-dom'; // standard TypeScript syntax
import { LocaleProvider } from 'k2-react-translate';
import { App } from './App';
import translations from './translations.json';
ReactDOM.render(
document.getElementById('app')
);
`
k2-react-translate barrels (re-exports) the following sub-modules as named exports:
A Context API wrapper to . This wrapper is required to applyk2-react-translate translations.
| Props | Type | Description |
| ----------------- | ----------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| translations | Object (required) | See translations under Project Setup |languages
| | Arrayparams to react-router if you choose to incorporate localized routing into your app. |defaultLanguage
| | string (optional) | Default language, Must be included in the languages array above |localizedUrls
| | boolean (optional), default={false} | Option to localize URLs with every route change, page reload or language change. Additionally, add a wrapper from react-router, meaning this need not be done in your RouterConfig |
#### Usage
See Project Setup above.
---
A custom hook for use in Function Components.
Dependencies: react@^16.8.0, react-dom@^16.8.0
#### Usage
`tsx
// MyComponent.tsx
import * as React from 'react'; // standard TypeScript syntax
import { useTranslate } from 'k2-react-translate';
const links = {
en: '/en/privacy-policy',
fr: '/fr/privacy-policy',
};
const MyComponent: React.FunctionComponent<{}> = () => {
const { translate, translateAndParse, language, changeLanguage } = useTranslate
const handleClick = (): void => {
// change language to French
changeLanguage('fr');
};
return (
---
$3
A React component that wraps
that performs translations, given
translation keys as prop arguments.If using
react v16.8.0+, I'd strongly recommend using the useTranslate hook
above instead. useTranslate works in the same way but provides for
cleaner and less verbose use.| Props | Type | Description |
| ----------- | ----------------------------------- | ---------------------------------------------------------------------------- |
|
id | string (optional) | translation key |
| vars | object (optional) | dynamic translation variables, set outside the translations.json |
| render | function (optional) | render prop, returning (language:string)=>ReactNode |
| parseHtml | boolean (optional), default=false | option to sanitize and parse stringified HTML set in the translations.json |#### Usage
`tsx
// MyComponent.tsx
import * as React from 'react'; // standard TypeScript syntax
import { Translator } from 'k2-react-translate';const links = {
en: '/en/privacy-policy',
fr: '/fr/privacy-policy',
};
const MyComponent: React.StatelessComponent<{}> = () => {
return (
// "Hello" (en) - string // "Bonjour" (fr) - string
// "Hello, Jaqen" (en) - string // "Bonjour, Jaqen" (fr) - string
// Privacy Policy (en) - ReactElement //
Politique de Confidentialité
(fr) - ReactElement
);
};
`---
$3
A button wrapped React component that provides the ability to set languages.
Switching languages can alternatively be performed under an exposed function in the
useTranslate
hook documented here.| Props | Type | Description |
| --------- | -------- | ---------------- |
|
onClick | Function | Synthentic event |#### Usage
`tsx
// MyComponent.tsx
import * as React from 'react'; // standard TypeScript syntax
import { LanguageSwitcher } from 'k2-react-translate';const MyComponent: React.FunctionComponent<{}>=()=>{
const handleClick:(changeLanguage: (language:string)=> void ): void=>{
// change language to French
changeLanguage('fr');
}
return
;
}
`Documentation (Localized Routing)
Localized routing is optional. If used,
react-router-dom would need to be installed as a
production dependency.$3
Provides a simple, non-intrusive way of setting up localized routes. Returns localized
s
or s components given the routes prop config.If
is used, you need not wrap your RouterConfig with or
as this is done within . is not recursive.| Props | Type | Description |
| ------------- | ----------------------------------- | -------------------------------------------------------------------------- |
|
routes | Array (required) | Based on react-router-dom's props |
| localize | Boolean (optional), default=true | Option to localize URLs (prepend the language code in the URL) |
| applySwitch | Boolean (optional), default=false | Wrap the Route config with components. Required in most cases. |#### Usage
`tsx
// RouteConfig.tsx
import * as React from 'react'; // standard TypeScript syntax
import { LocalizedRoutes, Route } from 'k2-react-translate';const RouteConfig: React.FunctionComponent<{}> = () => {
const routes: Route[] = [
{
path: '/', // resolves to /:language/, unless localize={false}
exact: true,
component: Home,
},
{
path: '/about', // resolves to /:language/about, unless localize={false}
component: About,
localize: true, // should override
},
{
// Redirect props
to: '/page-not-found', // resolves to /:language/page-not-found, unless localize={false}
},
];
return (
);
};
`---
$3
A localized wrapper to
react-router-dom's Route.You wouldn't need to use
if is
configured.| Props | Type | Description |
| ---------- | ---------------------------------- | ------------------------------------------------------------------------------------------- |
| ...props | Object | Standard
component props |
| localize | Boolean (optional), default=true | Option to localize URLs (prepend the language code in the URL) |#### Usage
`tsx
// MyComponent.tsx
import * as React from 'react'; // standard TypeScript syntax
import { LocalizedRoute } from 'k2-react-translate';
import { Home } from './Home';
import { About } from './About';const MyComponent: React.FunctionComponent<{}> = () => {
return (
// automatically resolves to the "/:language" // if "en" is active, then "/en"
// automatically resolves to the "/:language/about-us" // if "en" is active, then
"/en/about-us"
);
};
`---
$3
A localized wrapper to
react-router-dom's .| Props | Type | Description |
| ---------- | ---------------------------------- | ----------------------------------------------------------------------------------------- |
| ...props | Object | Standard
component props |
| localize | Boolean (optional), default=true | Option to localize URLs (prepend the language code in the URL) |#### Usage
`tsx
// MyComponent.tsx
import * as React from 'react'; // standard TypeScript syntax
import { LocalizedLink } from 'k2-react-translate';const MyComponent: React.FunctionComponent<{}> = () => {
return (
// automatically resolves to the "/:language/about-us" // if "en" is active, then
"/en/about-us"
About Us
);
};
`---
$3
A localized wrapper to
react-router-dom's .| Props | Type | Description |
| ---------- | ---------------------------------- | ------------------------------------------------------------------------------------------------- |
| ...props | Object | Standard
component props |
| localize | Boolean (optional), default=true | Option to localize URLs (prepend the language code in the URL) |#### Usage
`tsx
// MyComponent.tsx
import * as React from 'react'; // standard TypeScript syntax
import { LocalizedRedirect } from 'k2-react-translate';const MyComponent: React.FunctionComponent<{}> = () => {
// automatically resolves to the "/:language/page-not-found"
// if "en" is active, then "/en/page-not-found"
if (someCondition) {
return About Us ;
}
// alternatively,
props.history.push would also resolve URLs by current langauge return
;
};
`Development
- Run
yarn on the root of the repository.
- Run yarn start to start the project.
- Run yarn test:watch to ammend tests.Known Issues
- Routing works with
for now
- is yet to be adapted from . works equally as
well, with the exception of the activeClassName prop.