I'm building an online gallery in React, and it requires an external script in order to work properly.
There are 2 main components, namely Home.js and Single.js. Home.js displays some categories the images are organized in, and the Single.js is the detail view of a category (it contains all the photos under a specific category). The Router looks like this:
<Provider store={ store }>
<Router
forceRefresh={ false }>
<div id="router">
<Switch>
<Route exact path='/' render={ () => <MainLayout><Home /></MainLayout> } />
<Route exact path='/about' render={ () => <MainLayout><About /></MainLayout> } />
<Route path='/single/:id' render={ (props) => <MainLayout><Single {...props} /></MainLayout> } />
</Switch>
</div>
</Router>
</Provider>
I am loading the script 'main.js' using this function:
appendScripts() {
const main = document.createElement('script');
main.src = '/js/main.js';
main.async = true;
main.id = 'main';
document.body.appendChild(main);
}
Now the thing is that the script loads on the Home.js component, but it won't load on the Single.js component only the second time I access it through the home page (for the same category), even though it is appended in the DOM. And the same thing goes for accessing the home page through Single.js. If Single.js loads first, I need to access the Home.js 2 times through the Single.js for the script to load properly.
The components both have these functions called:
componentDidMount() {
this.appendScripts();
}
componentWillMount() {
this.props.getImages(this.state.id);
this.props.getCategory(this.state.id);
}
Any thoughts?