Skip to content

Commit b27cab7

Browse files
authored
Preserve children of wrapped component if translation value is null (#154)
1 parent 8c16c99 commit b27cab7

File tree

2 files changed

+38
-1
lines changed

2 files changed

+38
-1
lines changed

fluent-react/src/localized.js

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -111,10 +111,21 @@ export default class Localized extends Component {
111111
}
112112
}
113113

114-
if (messageValue === null || !messageValue.includes('<')) {
114+
// If the message has a null value, we're onl interested in its attributes.
115+
// Do not pass the null value to cloneElement as it would nuke all children
116+
// of the wrapped component.
117+
if (messageValue === null) {
118+
return cloneElement(elem, localizedProps);
119+
}
120+
121+
// If the message value doesn't contain any markup, insert it as the only
122+
// child of the wrapped component.
123+
if (!messageValue.includes('<')) {
115124
return cloneElement(elem, localizedProps, messageValue);
116125
}
117126

127+
// If the message contains markup, parse it and try to match the children
128+
// found in the translation with the props passed to this Localized.
118129
const translationNodes = Array.from(parseMarkup(messageValue).childNodes);
119130
const translatedChildren = translationNodes.map(childNode => {
120131
if (childNode.nodeType === childNode.TEXT_NODE) {

fluent-react/test/localized_render_test.js

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -196,6 +196,32 @@ foo =
196196
));
197197
});
198198

199+
test('preserve children when translation value is null', function() {
200+
const mcx = new MessageContext();
201+
const l10n = new ReactLocalization([mcx]);
202+
203+
mcx.addMessages(`
204+
foo =
205+
.title = TITLE
206+
`)
207+
208+
const wrapper = shallow(
209+
<Localized id="foo" attrs={{title: true}}>
210+
<select>
211+
<option>Option</option>
212+
</select>
213+
</Localized>,
214+
{ context: { l10n } }
215+
);
216+
217+
assert.ok(wrapper.contains(
218+
<select title="TITLE">
219+
<option>Option</option>
220+
</select>
221+
));
222+
});
223+
224+
199225
test('$arg is passed to format the value', function() {
200226
const mcx = new MessageContext();
201227
const format = sinon.spy(mcx, 'format');

0 commit comments

Comments
 (0)