Reputation: 59
This seems to be a common problem according to the creator of GatsbyJS. Here's a quote from a resolved issue on the GitHub repo:
You have code (either your own or a module you're using) which is referencing the window object. This fails when server rendering as you're not in a browser so window doesn't exist. This is a fairly common problem. The solution is to run code references to the window in componentDidMount where you can be sure you're now in a browser.
I've seen only a handful of examples setting up AOS in ReactJS or setting up similar things in GatsbyJS but nothing exactly what I need. The config I've come up with just doesn't work for the production build aka "gatsby build" ... Here's my code:
import React from 'react'
import {Link} from 'react-router'
import {prefixLink} from 'gatsby-helpers'
import {config} from 'config'
import AOS from 'aos'
import '../static/css/reset.css'
import '../static/css/typography.css'
import '../static/css/base.css'
import '../static/css/w3.css'
import '../static/css/aos.css'
import '../static/css/devicons.css'
class Template extends React.Component {
componentDidMount() {
AOS.init()
}
render() {
const {location, children} = this.props
return (
<div>
<div className='wrapper'>
{children}
</div>
</div>
);
}
}
Template.propTypes = {
children: React.PropTypes.any,
location: React.PropTypes.object,
route: React.PropTypes.object
}
export default Template
I've tried a few variations where I set a variable in the props constructor to AOS then use componentDidMount to set the variable to AOS.init(), also tried using this.state and setting that but neither made any difference. So what's the proper way to do what's required? I know I'm going to use componentDidMount but beyond that I dunno. Any help is much appreciated...
Upvotes: 1
Views: 4460
Reputation: 49
I modified @floroz's answer a little bit, because I see for him AOS will always be undefined outside the first useEffect and here the code
let AOS;
useEffect(() => {
AOS = require("aos");
AOS.init();
}, [])
useEffect(() => {
if (AOS) {
AOS.refresh();
}
});
Upvotes: 0
Reputation: 413
I solved it using React Hooks (16.8+)
let AOS;
useEffect(() => {
/**
* Server-side rendering does not provide the 'document' object
* therefore this import is required either in useEffect or componentDidMount as they
* are exclusively executed on a client
*/
const AOS = require("aos");
AOS.init({
once: true,
});
}, []);
useEffect(() => {
if (AOS) {
AOS.refresh();
}
});
Upvotes: 2
Reputation: 59
I finally realized that I had forgotted how another starter Gatsby project handled Wow.js... This is what fixed my issue, based of their example in the Gatstrap, Gatsby starter blog:
componentDidMount() {
const AOS = require('aos');
this.aos = AOS
this.aos.init()
}
componentDidUpdate() {
this.aos.refresh()
}
Hope this helps someone else!
Upvotes: 4