When the page loads I use componentDidMount() to document.createElement(\"script\");
in the layout index.js
of a ReactJS and G
componentDidMount
runs the first time (and only the first time!) the component is mounted in the DOM.
componentDidUpdate
runs every time the component receives new props, but not for the initial render.
In order to operate on the DOM for the first render and for subsequent updates, you'll need to register your handling logic in both
componentDidMount
and componentDidUpdate
, i.e.
class YourComponent extends React.Component {
componentDidMount () {
const tripadvisorLeft = document.createElement("script");
tripadvisorLeft.src = "https://www.jscache.com/wejs?wtype=selfserveprop&uniq=789&locationId=10467767&lang=en_NZ&rating=true&nreviews=0&writereviewlink=true&popIdx=true&iswide=true&border=false&display_version=2";
tripadvisorLeft.async = true;
document.body.appendChild(tripadvisorLeft);
// Keep track of the script tag
this.scriptTag = tripadvisorLeft
}
componentDidUpdate (prevProps) {
// Figure out if the path changed
if (this.props.path !== prevProps.path) {
// Remove the old script tag
document.body.removeChild(this.scriptTag)
// Add it back
const tripadvisorLeft = document.createElement("script");
tripadvisorLeft.src = "https://www.jscache.com/wejs?wtype=selfserveprop&uniq=789&locationId=10467767&lang=en_NZ&rating=true&nreviews=0&writereviewlink=true&popIdx=true&iswide=true&border=false&display_version=2";
tripadvisorLeft.async = true;
document.body.appendChild(tripadvisorLeft);
this.scriptTag = tripadvisorLeft
}
}
}
You can refactor this to move the creation logic into a helper function, but I've inlined it here to make it clear what's going on.