@@ -121,22 +121,30 @@ function ScriptElement({ model }: { model: ReactPyVdom }) {
121
121
if ( ! ref . current ) {
122
122
return ;
123
123
}
124
- const scriptContent = model ?. children ?. filter (
124
+
125
+ const element : HTMLScriptElement = document . createElement ( "script" ) ;
126
+ const content = model ?. children ?. filter (
125
127
( value ) : value is string => typeof value == "string" ,
126
128
) [ 0 ] ;
127
129
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
129
135
for ( const [ k , v ] of Object . entries ( model . attributes || { } ) ) {
130
- scriptElement . setAttribute ( k , v ) ;
136
+ element . setAttribute ( k , v ) ;
131
137
}
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 ) ;
134
141
}
135
- ref . current . appendChild ( scriptElement ) ;
142
+ // Render the script element
143
+ ref . current . appendChild ( element ) ;
136
144
} , [ model . key ] ) ;
137
145
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 .
140
148
return < div ref = { ref } /> ;
141
149
}
142
150
0 commit comments