Reputation: 21
I'm trying to add a custom masonry script to a single page in Gatsby. It makes modifications to styling properties of <div>
elements in a grid layout, but it essentially the script needs to do its thing every time the page is loaded or resized.
The way I'm trying to accomplish this is via requiring the script in an effect hook in a function returning a React component:
// in 'page.js'
export default () => {
useEffect(() => {
require('./scripts/masonry');
}
return // blah blah blah...
}
And in the script, I've put all the things I need the script to do in a function called resizeAll
and attached it to window.onloadend
and added it to a resize event listener:
// in the masonry script at the very bottom
window.onloadend = resizeAll;
window.addEventListener('resize', resizeAll);
But this doesn't work because the script seems to run only when the page is resized, but not when loading or navigating to the page. My suspicion is that window.onloadend
is for some reason broken or clobbered by gatsby's functionality, or that I'm not using it right. Any help would be much appreciated.
Upvotes: 2
Views: 3713
Reputation: 21
Turns out I solved the problem! Hooks didn't seem to be doing the trick, so I stuck the resizeAll
function in the onRouteUpdate export in gatsby-browser
.
Like Ferran Buireu said, this is a workaround, but my site is pretty small and so far I haven't noticed any severe detriment to performance, but I will rebuild the script later if need be...
Upvotes: 0
Reputation: 2321
You can do it using React Helmet which basically writes things into your html pages <head>
tag. Also you will need Gatsby's withPrefix
for resolving the path to the script which comes built-in with Gatsby.
Most likley the Gatsby starter you are using has React Helmet already setup (look at your package.json
). If this is the case simply put your script in the /static/
folder for your project and then in React include the script into the <head>
of your page like this:
import Helmet from "react-helmet";
import { withPrefix } from "gatsby";
<Helmet>
<script src={withPrefix('masonry.js')} />
</Helmet>
If for some reason your Gatsby project doesn't already have React Helmet setup then you can setup by following the instructctions here.
Upvotes: 1