File tree 1 file changed +15
-6
lines changed
src/js/packages/@reactpy/client/src
1 file changed +15
-6
lines changed Original file line number Diff line number Diff line change @@ -120,21 +120,30 @@ function ScriptElement({ model }: { model: ReactPyVdom }) {
120
120
const ref = useRef < HTMLDivElement | null > ( null ) ;
121
121
122
122
React . useEffect ( ( ) => {
123
- if ( ! ref . current ) {
124
- return ;
125
- }
123
+ // Fetch the script's content
126
124
const scriptContent = model ?. children ?. filter (
127
125
( value ) : value is string => typeof value == "string" ,
128
126
) [ 0 ] ;
129
127
128
+ // Don't run if the parent element or script content is missing
129
+ if ( ! ref . current || ! scriptContent ) {
130
+ return ;
131
+ }
132
+
133
+ // Create the script element
130
134
const scriptElement : HTMLScriptElement = document . createElement ( "script" ) ;
131
135
for ( const [ k , v ] of Object . entries ( model . attributes || { } ) ) {
132
136
scriptElement . setAttribute ( k , v ) ;
133
137
}
134
- if ( scriptContent ) {
135
- scriptElement . appendChild ( document . createTextNode ( scriptContent ) ) ;
136
- }
138
+
139
+ // Append the script content to the script element
140
+ scriptElement . appendChild ( document . createTextNode ( scriptContent ) ) ;
137
141
ref . current . appendChild ( scriptElement ) ;
142
+
143
+ // Remove the script element when the component is unmounted
144
+ return ( ) => {
145
+ ref . current ?. removeChild ( scriptElement ) ;
146
+ } ;
138
147
} , [ model . key ] ) ;
139
148
140
149
return < div ref = { ref } /> ;
You can’t perform that action at this time.
0 commit comments