@@ -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
0 commit comments