Skip to content

Commit 75e1c76

Browse files
committed
Strictly validate children
1 parent 1803c30 commit 75e1c76

File tree

3 files changed

+19
-6
lines changed

3 files changed

+19
-6
lines changed

fluent-react/src/localized.ts

+13-4
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { ReactElement, ReactNode, createElement } from "react";
1+
import { ReactElement, ReactNode, createElement, isValidElement } from "react";
22
import PropTypes from "prop-types";
33
import { FluentVariable } from "@fluent/bundle";
44
import { LocalizedElement } from "./localized_element";
@@ -22,9 +22,18 @@ export function Localized(props: LocalizedProps): ReactElement {
2222
return createElement(LocalizedText, props);
2323
}
2424

25-
// Redirect to LocalizedElement for element children. Only a single element
26-
// child is supported; LocalizedElement enforces this requirement.
27-
return createElement(LocalizedElement, props);
25+
if (isValidElement(props.children)) {
26+
// Redirect to LocalizedElement for element children. Only a single element
27+
// child is supported; LocalizedElement enforces this requirement.
28+
return createElement(LocalizedElement, props);
29+
}
30+
31+
throw new Error(
32+
"<Localized> can be used either similar to <LocalizedElement>, " +
33+
"in which case it expects a single React element child, or similar to " +
34+
"<LocalizedText>, in which case it expects a single string-typed child " +
35+
"or no children at all."
36+
);
2837
}
2938

3039
Localized.propTypes = {

fluent-react/src/localized_element.ts

+1-2
Original file line numberDiff line numberDiff line change
@@ -50,8 +50,7 @@ export function LocalizedElement(props: LocalizedElementProps): ReactElement {
5050

5151
// Check if the child inside <LocalizedElement> is a valid element.
5252
if (!isValidElement(child)) {
53-
throw new Error("<LocalizedElement/> expected to receive a single " +
54-
"React element child");
53+
throw new Error("<LocalizedElement> expected a single React element child");
5554
}
5655

5756
const l10n = useContext(FluentContext);

fluent-react/src/localized_text.ts

+5
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,11 @@ export interface LocalizedTextProps {
3535
export function LocalizedText(props: LocalizedTextProps): ReactElement {
3636
const { id, vars, children: child = null } = props;
3737

38+
if (child !== null && typeof child !== "string") {
39+
throw new Error("<LocalizedText> expected a single string-typed child " +
40+
"or no children.");
41+
}
42+
3843
const l10n = useContext(FluentContext);
3944
if (!l10n) {
4045
// Use the child as fallback.

0 commit comments

Comments
 (0)