React Intl - Creating an input that needs a placeholder attribute to be translated

1.3k Views Asked by At
const Input = props => (
  <InputWrapper
    skew={props.skew}
  >
    <InputElement
      skew={props.skew}
      placeholder={props.placeholder}
      type={props.type}
    />
  </InputWrapper>
);

I'm trying to find an example online explaining how I use the <FormattedMessage id="" defaultMessage="" /> component for placeholders. We have JSON files where we set the different languages for it to point to. So as an example that I have above the ID would point to the json file and then into that object to pick the right value for the language. So we'd have multiple json files for each language.

How would we go about doing this for a placeholder attribute as I need to return a string instead.

1

There are 1 best solutions below

0
On

If I assume it correctly:

  • You have translations in a JSON file.
  • The id specifies the translation
  • You want to use the translated message as the defaultMessage property of a FormattedMessage component

If that is incorrect please comment. If it's correct i would:

  • Create a function in some util file that gets me the translation
  • Create a custom component that wraps the FormattedMessage component

In some util.jsx file:

const getTranslationFromId(id) = (id) => {
    // Get translation from JSON file here!
    const translatedMessage = ...; 

    return translatedMessage;
}

In FormattedTranslatedMessage.jsx:

import React from "react";
import {getTranslationFromId} from "../some/path/to/utils";

const FormattedTranslatedMessage = ({id, ...restProps}) => (
    <FormattedMessage defaultMessage={getTranslationFromId(id)} {...restProps} />
);

export default FormattedTranslatedMessage;

Please comment if my suggestions are wrong or i could improve the answer...