Skip to content

Commit 93a1d0a

Browse files
committed
cleanup code
1 parent b6385d2 commit 93a1d0a

File tree

2 files changed

+20
-13
lines changed

2 files changed

+20
-13
lines changed

src/js/packages/@reactpy/client/src/components.tsx

Lines changed: 16 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -121,22 +121,30 @@ function ScriptElement({ model }: { model: ReactPyVdom }) {
121121
if (!ref.current) {
122122
return;
123123
}
124-
const scriptContent = model?.children?.filter(
124+
125+
const element: HTMLScriptElement = document.createElement("script");
126+
const content = model?.children?.filter(
125127
(value): value is string => typeof value == "string",
126128
)[0];
127129

128-
const scriptElement: HTMLScriptElement = document.createElement("script");
130+
// Add the script text if it exists
131+
if (content) {
132+
element.appendChild(document.createTextNode(content));
133+
}
134+
// Add all attributes to the script element
129135
for (const [k, v] of Object.entries(model.attributes || {})) {
130-
scriptElement.setAttribute(k, v);
136+
element.setAttribute(k, v);
131137
}
132-
if (scriptContent) {
133-
scriptElement.appendChild(document.createTextNode(scriptContent));
138+
// Remove all previous script elements
139+
while (ref.current.firstChild) {
140+
ref.current.removeChild(ref.current.firstChild);
134141
}
135-
ref.current.appendChild(scriptElement);
142+
// Render the script element
143+
ref.current.appendChild(element);
136144
}, [model.key]);
137145

138-
// FIXME: We currently return an extraneous div to attach the script to, but there
139-
// might be a better way to do this.
146+
// We return an extraneous div to attach the script to since ReactJS does not allow
147+
// script tags to be executed when rendered directly.
140148
return <div ref={ref} />;
141149
}
142150

src/py/reactpy/reactpy/html.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -437,13 +437,12 @@ def _script(
437437
if len(children) > 1:
438438
msg = "'script' nodes may have, at most, one child."
439439
raise ValueError(msg)
440-
elif not isinstance(children[0], str):
440+
if not isinstance(children[0], str):
441441
msg = "The child of a 'script' must be a string."
442442
raise ValueError(msg)
443-
else:
444-
model["children"] = children
445-
if key is None:
446-
key = children[0]
443+
model["children"] = children
444+
if key is None:
445+
key = children[0]
447446

448447
if attributes:
449448
model["attributes"] = attributes

0 commit comments

Comments
 (0)