How to use dynamic strings in a localization message in React?

When localizing messages in a React application, it is often necessary to insert dynamic strings that change based on the context or user input. To achieve this, placeholders can be used in the localization message.

For example, instead of hardcoding a string like "Hello, John!" in the message, we can use a placeholder like "{name}" and replace it with the actual name at runtime. To use dynamic strings and placeholders in a localization message, we can define the message with the placeholders in the localization files, and then use a localization library in our React components to substitute the placeholders with the actual values at runtime.

The localization message:

"common.greeting": "Hello, {name}!"

The usage in code:

const intl = useIntl();
const message = intl.formatMessage({ id: "common.greeting" }, { name: "Eric" });

React internationalization tutorial:

Copyrights 2024 © Localizely