
Research
/Security News
Critical Vulnerability in NestJS Devtools: Localhost RCE via Sandbox Escape
A flawed sandbox in @nestjs/devtools-integration lets attackers run code on your machine via CSRF, leading to full Remote Code Execution (RCE).
react-intl-hooks
Advanced tools
React-intl-hooks is a small and fast library of hooks that you can use to replace all the Format.js components. This helps you have a consistent codebase if you're using the latest React.js features!.
Format.js with react-intl is an awesome library but for the people like us that loves React new features like hooks, it's a bit daunting to still use libraries that have components. So we decided to combine the great things that the react-intl team did with React hooks.
Yarn
yarn add react-intl-hooks
NPM
npm install react-intl-hooks
First we need to enable internationalization in our app. We need to import the IntlProvider
component, then use it to wrap our React app.
Your src/index.js
should look like this:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import { IntlProvider } from 'react-intl-hooks';
import locale_en from './translations/en.json';
import locale_es from './translations/es.json';
const data = {
es: locale_es,
en: locale_en,
};
const language = navigator.language.split(/[-_]/)[0];
ReactDOM.render(
<React.StrictMode>
<IntlProvider
locale={language}
messages={data[language]}
defaultLocale="en"
>
<App />
</IntlProvider>
</React.StrictMode>,
document.getElementById('root'),
);
We import all our translations files and we get the locale from the users browser. In case the locale is not available we'll default to en as our locale.
Create src/translations
folder in your project and create files for the locales you want to add support in you React app.
We are going to create create translations files for English and Spanish.
Here's the contet we placed in our files.
src/translations/en.json
:{
"app.learn": "Learn React"
}
src/translations/es.json
:{
"app.learn": "Aprende React"
}
Translating your components it's just as easy as importing the hook you need.
src/app.js
:
import React from 'react';
import logo from './logo.svg';
import './App.css';
import { useFormatMessage } from 'react-intl-hooks';
function App() {
const t = useFormatMessage();
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
{t({ id: 'app.learn', defaultMessage: 'Learn React' })}
</a>
</header>
</div>
);
}
export default App;
In the last example we simply translate the default app you get when you use create-react-app
to boostrap your project.
Your have a wide variety of hooks to choose depending the things you want to translate.
import {
useFormatMessage,
useFormatDate,
useFormatList,
useFormatNumber,
useFormatPlural,
useFormatRelativeTime,
useFormatTime,
} from 'react-intl-hooks';
We'll have a detail look on each one in the next section.
Here you'll get a detail explanation of every hook react-intl-hooks
has to offer.
useFormatMessage
Hook used to translate texts in your application.
Import the hook:
import { useFormatMessage } from 'react-intl-hooks';
Then use it like this:
const t = useFormatMessage(
{
id: 'app.greeting',
defaultMessage: 'Hello, {name}!',
description: 'Greeting to welcome the user to the app',
},
{ name: 'Eric' },
); // "Hello, Eric!"
The hook return a translation function that can be used inside your JSX code of your components.
t(message: MessageDescriptor, values?: MessageFormatValues);
{
id: string,
description?: string,
defaultMessage?: string
}
Object used to pass variables or React elements to our translated text. In the following example you can see a use case for this.
import React from 'react';
import { useFormatMessage } from 'react-intl-hooks';
const MyComponent = () => {
const t = useFormatMessage();
return (
<div>
<h1>
{t(
{
id: 'mycomponent.title',
description: 'Title for my component!',
defaultMessage: 'Hello {user}!',
},
{ user: 'Mateo' },
)}
</h1>
</div>
);
};
export default MyComponent;
<div>
<h1>Hello Mateo!</h1>
</div>
useFormatDate
This hook is used to translate a date into the users locale.
Import the hook:
import { useFormatDate } from 'react-intl-hooks';
Then use it like this:
const t = useFormatDate(Date.now(), {
year: 'numeric',
month: 'numeric',
day: 'numeric',
}); // "3/4/2016"
The hook return a translation function that can be used inside your JSX code of your components.
t(value: DateFormatPrimitiveValue, options?: FormatDateOptions);
The date to be translated, it can have the following types: Date
, number
or string
.
Object containing formating options of the time to be translated. Each property is optional and can recieve the following values: short
or numeric
.
{
year?: string,
month?: string,
day?: string,
hour?: string,
minute?: string,
second?: string,
weekday?: string,
era?: string
}
In the following example you see how can you use the formatting options.
import React from 'react';
import { useFormatDate } from 'react-intl-hooks';
const MyComponent = () => {
const t = useFormatDate();
const todayDate = new Date('3/4/2016');
return (
<div>
<h1>
{t(todayDate, {
weekday: 'short',
year: 'numeric',
month: 'short',
day: 'numeric',
})}
</h1>
</div>
);
};
export default MyComponent;
<div>
<h1>Fri, Mar 4, 2016</h1>
</div>
useFormatTime
This hook is used to format a time into the user locale.
Import the hook:
import { useFormatTime } from 'react-intl-hooks';
Then use it like this:
const t = useFormatTime(Date.now()); // "4:03 PM"
The hook return a translation function that can be used inside your JSX code of your components.
t(value: TimeFormatPrimitiveValue, options?: FormatDateOptions);
The time to be translated, it can have the following types: Date
or number
.
Object containing formating options of the time to be translated. Each property is optional and can recieve the following values: short
or numeric
.
{
year?: string,
month?: string,
day?: string,
hour?: string,
minute?: string,
second?: string,
weekday?: string,
era?: string
}
In the following example you see how can you use the formatting options.
import React from 'react';
import { useFormatTime } from 'react-intl-hooks';
const MyComponent = () => {
const t = useFormatTime();
const todayDate = new Date('3/4/2016');
return (
<div>
<h1>{t(todayDate)}</h1>
</div>
);
};
export default MyComponent;
<div>
<h1>12:00 AM</h1>
</div>
useFormatNumber
This hook is used to format numbers into the user locale.
Import the hook:
import { useFormatNumber } from 'react-intl-hooks';
Then use it like this:
const t = useFormatNumber(0.5, { style: 'percent' }); // "50%"
The hook return a translation function that can be used inside your JSX code of your components.
t(value: number, options?: FormatNumberOptions);
The number to be formatted into the user locale.
Object containing formating options of the number to be translated. Each property is optional.
{
style?: string,
unit?: string,
unitDisplay?: string,
currency?: string
}
currency
(e.g., $1,000).unit
and unitDisplay
(e.g., 1,000kB).style
property is set to "unit". Possible values are almost 27 units, we'll show some of all the possible values:
style
is set to "currency". Possible values are the ISO 4217 abbreviations of the currencies:
In the following example you see how can you use the formatting options.
import React from 'react';
import { useFormatNumber } from 'react-intl-hooks';
const MyComponent = () => {
const t = useFormatNumber();
return (
<div>
<h1>{t(1000, { style: 'currency', currency: 'USD' })}</h1>
</div>
);
};
export default MyComponent;
<div>
<h1>$1,000.00</h1>
</div>
useFormatRelativeTime
This hook recieves a number formats it into a relative time.
Import the hook:
import { useFormatRelativeTime } from 'react-intl-hooks';
Then use it like this:
const t = useFormatRelativeTime(1, 'hour'); // "in 1 hour"
The hook return a translation function that can be used inside your JSX code of your components.
t(value: number, unit?: Unit, options?: FormatNumberOptions);
The number to be formatted into a relative time matching the use locale.
The unit of the number to be formatted. It can have the following values: second
, minute
, hour
, day
, week
, month
, quarter
or year.
Object containing formating options of the time to be transformed into a relative time. Each property is optional.
{
numeric?: string,
style?: string
}
import React from 'react';
import { useFormatRelativeTime } from 'react-intl-hooks';
const MyComponent = () => {
const t = useFormatRelative();
return (
<div>
<h1>{t(1, 'hour')}</h1>
</div>
);
};
export default MyComponent;
<div>
<h1>in 1 hour</h1>
</div>
useFormatList
This hook allows you to join list of things together in an i18n-safe way.
Import the hook:
import { useFormatList } from 'react-intl-hooks';
Then use it like this:
const t = useFormatList(['5 hours', '3 minutes'], { type: 'unit' }); // 5 hours, 3 minutes
The hook return a translation function that can be used inside your JSX code of your components.
t(value: string[], options?: FormatListOptions);
Array of strings to be joined together.
Object containing formating options for the list to be formatted. Each property is optional.
{
type?: string,
style?: string
}
import React from 'react';
import { useFormatList } from 'react-intl-hooks';
const MyComponent = () => {
const t = useFormatList();
return (
<div>
<h1>{t(['5 hours', '3 minutes'], { type: 'unit' })}</h1>
</div>
);
};
export default MyComponent;
<div>
<h1>5 hours, 3 minutes</h1>
</div>
useFormatPlural
This hook will return a plural category string: "zero", "one", "two", "few", "many", or "other".
Note: This hook should only be used in apps that only need to support one language. If your app supports multiple languages use useFormatMessage
instead.
Import the hook:
import { useFormatPlural } from 'react-intl-hooks';
Then use it like this:
const t = useFormatPlural(2, { style: 'ordinal' }); // "two"
The hook return a translation function that can be used inside your JSX code of your components.
t(value: number, options?: FormatPluralOptions);
Number to be pluralized.
Object containing formating options for the number to be formatted. The property is optional.
{
type?: string,
}
type: the type of the output message. Possible values are:
import React from 'react';
import { useFormatPlural } from 'react-intl-hooks';
const MyComponent = () => {
const t = useFormatPlural();
return (
<div>
<h1>{t(2, { style: 'ordinal' })}</h1>
</div>
);
};
export default MyComponent;
<div>
<h1>two</h1>
</div>
We'd like to thank these awesome people who made this whole thing happen. [Become a contributor]
This project is licensed under the MIT license, Copyright (c) 2020 CreateThrive. [License]
FAQs
React hooks for internationalization without the hassle
The npm package react-intl-hooks receives a total of 360 weekly downloads. As such, react-intl-hooks popularity was classified as not popular.
We found that react-intl-hooks demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Research
/Security News
A flawed sandbox in @nestjs/devtools-integration lets attackers run code on your machine via CSRF, leading to full Remote Code Execution (RCE).
Product
Customize license detection with Socket’s new license overlays: gain control, reduce noise, and handle edge cases with precision.
Product
Socket now supports Rust and Cargo, offering package search for all users and experimental SBOM generation for enterprise projects.