I can't find anything in the react-intl
docs (I'm using v2
branch) regarding this kind of usage, hence this issue. Is there a recommended approach for the following use-case?
Say I have 2 components, Tooltip
and Select
. Both require the same i18n-formatted string, say something like:
<FormattedMessage
id='ui.widget.cycleOffsetSelector.timeCycle.label'
defaultMessage="This {cycle}"
values={{cycle: props.cycle}}
/>
How do I use the same message in the other component? Just using this:
<FormattedMessage
id='ui.widget.cycleOffsetSelector.timeCycle.label'
values={{cycle: props.cycle}}
/>
does not work (should not :) ). So, what is the correct way to do this?
Do I have to keep these shared messages somewhere globally in my app? Because it can become cumbersome maintaining a list of "shared" intl messages separate from the code, the very thing which react-intl
claims to solve.
In react-intl v2 the message ids are static so no 2 ids can be alike. The thought is to keep assets that are being used in the components in the same file for easy development. Then extract the strings at build time for translation. Many times this problem can be solved by creating a higher order component (HOC) or creating a component to reuse instead of reusing a message string.
If creating a HOC is not an option here are a few more ways to handle this issue:
You can use defineMessages() in a centralized messages file to define common strings that you reuse, keeping strings that are only for specific components in those components.
Namespacing ids is also a possibility.
ui.widget.cycleOffsetSelector.timeCycle.select.label ui.widget.cycleOffsetSelector.timeCycle.tooltip.label
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With