Needing a solution to a problem that I have asked in many ways without resolve.
I have external scripts from TripAdvisor that are being mounted in a component as componentDidMount
. Also shouldComponentUpdate()
as false
to avoid future eventListeners
also mounted by componentDidMount
in the layouts/index.js
from affecting the TripAdvisor content to disappear due to re-render of the DOM.
componentDidMount () {
const tripadvisorLeft = document.createElement("script");
tripadvisorLeft.src = "https://www.jscache.com/wejs?wtype=selfserveprop&uniq=789&locationId=10467767&lang=en_AU&rating=true&nreviews=0&writereviewlink=true&popIdx=true&iswide=true&border=false&display_version=2";
document.body.appendChild(tripadvisorLeft);
const tripadvisorRight = document.createElement("script");
tripadvisorRight.src = "https://www.jscache.com/wejs?wtype=selfserveprop&uniq=998&locationId=10467767&lang=en_AU&rating=false&nreviews=4&writereviewlink=false&popIdx=false&iswide=true&border=false&display_version=2";
document.body.appendChild(tripadvisorRight);
}
shouldComponentUpdate() {
return false;
}
The problem is that when using Link
by either react-route
or gatsby-link
to and from the page that contains the component the content from TripAdvisor is not rendered.
If I refresh the browser on the page - the content is available. See here - example
How can I unmount
, forceUpdate
or any other solution to getting these scripts re-render on route change
?
Full source code can be found here .
It appears that the TripAdvisor script is creating a function called injectselfserveprop***
. (where ***
are random numbers).
This function is responsible to display the HTML code of the TripAdvisor widget.
However, for obscure reason this function is not called when you reach the Component with Link
.
This is one solution for your issue, and might not be the best:
Because the TripAdvisor ' script creates these functions, we have to define the scripts before rendering the TripAdvisor
component.
<Helmet>
// ...
<script src={`https://www.jscache.com/wejs?wtype=selfserveprop&uniq=789&locationId=10467767&lang=en_AU&rating=true&nreviews=0&writereviewlink=true&popIdx=true&iswide=true&border=false&display_version=2`}/>
<script src={`https://www.jscache.com/wejs?wtype=selfserveprop&uniq=998&locationId=10467767&lang=en_AU&rating=false&nreviews=4&writereviewlink=false&popIdx=false&iswide=true&border=false&display_version=2`}/>
</Helmet>
injectselfserveprop
functions on TripAdvisor
componentDidMount() componentDidMount() {
// find any function that begins with 'injectselfserveprop'
// and execute it.
Object.keys(window).forEach((key) => {
if (key.match(/^injectselfserveprop[0-9]+$/)) {
window[key]();
}
});
}
I have tried this and it works for me.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.