Categories
React Answers

How to Use React-Intl in an Input Placeholder?

Spread the love

Sometimes, we want to use React-Intl in an input placeholder.

In this article, we’ll look at how to use React-Intl in an input placeholder.

Use React-Intl in an Input Placeholder

To use React-Intl in an input placeholder, we can use the intl.formatMessage method with an object that has the message ID we want to display set as the value of the id property of the object.

For instance, we can write:

index.js

import { StrictMode } from "react";
import ReactDOM from "react-dom";
import { IntlProvider } from "react-intl";
import App from "./App";

const lang = "en";
const messages = {
  en: {
    placeholderMessageId: "placeholder in english"
  },
  fr: {
    placeholderMessageId: "placeholder en fançais"
  }
};

const rootElement = document.getElementById("root");
ReactDOM.render(
  <StrictMode>
    <IntlProvider locale={lang} messages={messages[lang]}>
      <App />
    </IntlProvider>
  </StrictMode>,
  rootElement
);

App.js

import { useIntl } from "react-intl";

export default function App() {
  const intl = useIntl();

  return (
    <input placeholder={intl.formatMessage({ id: "placeholderMessageId" })} />
  );
}

We wrap the IntlProvider around the App component so that we can use the useIntl hook in App to get the placeholder message for the language set with formatMessage .

The locale is the locale of the language we want to display.

messages has the messages for each language.

In App , we set the placeholder prop of the input to the return value of intl.formatMessage({ id: “placeholderMessageId” }) to set the placeholder to the message that corresponds to the key placeholderMessageId .

Therefore, placeholder in english is displayed as the placeholder of the input since lang is 'en' and placeholderMessageId for en is placeholder in english .

Conclusion

To use React-Intl in an input placeholder, we can use the intl.formatMessage method with an object that has the message ID we want to display set as the value of the id property of the object.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *