Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deal with multiple usage of a React-Intl message?

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.

like image 475
kumarharsh Avatar asked Jan 19 '16 12:01

kumarharsh


1 Answers

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

like image 177
slchap5 Avatar answered Sep 20 '22 20:09

slchap5