Skip to content

Commit 8a1f84e

Browse files
authored
[@fluent/react] Allow the Localized component to have an array with one element in its children property (#541)
[@fluent/react] Allow the `Localized` component to have an array with one element in its children property
2 parents f2d23f3 + 1e39c73 commit 8a1f84e

File tree

2 files changed

+26
-6
lines changed

2 files changed

+26
-6
lines changed

fluent-react/src/localized.ts

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ const reMarkup = /<|&#?\w+;/;
1919
export interface LocalizedProps {
2020
id: string;
2121
attrs?: Record<string, boolean>;
22-
children?: ReactNode;
22+
children?: ReactNode | Array<ReactNode>;
2323
vars?: Record<string, FluentVariable>;
2424
elems?: Record<string, ReactElement>;
2525
}
@@ -46,13 +46,23 @@ export interface LocalizedProps {
4646
* source code.
4747
*/
4848
export function Localized(props: LocalizedProps): ReactElement {
49-
const { id, attrs, vars, elems, children: child = null } = props;
49+
const { id, attrs, vars, elems, children = null } = props;
5050
const l10n = useContext(FluentContext);
51+
let child: ReactNode | null;
52+
53+
// Validate that the child element isn't an array that contains multiple
54+
// elements.
55+
if (Array.isArray(children)) {
56+
if (children.length > 1) {
57+
throw new Error("<Localized/> expected to receive a single " +
58+
"React node child");
59+
}
5160

52-
// Validate that the child element isn't an array
53-
if (Array.isArray(child)) {
54-
throw new Error("<Localized/> expected to receive a single " +
55-
"React node child");
61+
// If it's an array with zero or one element, we can directly get the first
62+
// one.
63+
child = children[0];
64+
} else {
65+
child = children;
5666
}
5767

5868
if (!l10n) {

fluent-react/test/localized_valid.test.js

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,16 @@ describe("Localized - validation", () => {
5757
expect(console.error).toHaveBeenCalled();
5858
});
5959

60+
test("with single children inside an array", () => {
61+
const renderer = TestRenderer.create(
62+
<LocalizationProvider l10n={new ReactLocalization([])}>
63+
<Localized children={[<div />]} />
64+
</LocalizationProvider>
65+
);
66+
67+
expect(renderer.toJSON()).toMatchInlineSnapshot(`<div />`);
68+
});
69+
6070
test("without id", () => {
6171
const renderer = TestRenderer.create(
6272
<LocalizationProvider l10n={new ReactLocalization([])}>

0 commit comments

Comments
 (0)