Closed farrellfileas closed 6 years ago
Have a look at these docs: https://next.gatsbyjs.org/docs/debugging-html-builds/#how-to-check-if-window-is-defined
On another note: imo there’s no reason to use jQuery if you use React. Why do you need jQuery?
Hey @LeKoArts,
I've actually already seen that page you linked but I'm still unsure how to implement it in my code.
As for using jQuery, I'm very new to React (and in fact to web programming entirely) so I'm still sticking to what I'm comfortable with since I'm on a deadline. As I progress I will stop using jQuery with React, it's just for my current assignment.
Hi @farrellfileas, to implement this in your code you would do the following:
componentDidMount(){
if (typeof window !== `undefined`) {
$(selector).blablabla();
}
}
You might also need to conditionally import jQuery - if the above code doesn't work on its own, replace the line import $ from "jquery"
with this:
let $;
if (typeof window !== `undefined`) {
$ = require("jquery");
}
As @LeKoArts says, it's not really a good idea to use jQuery with React - you might end up shooting yourself in the foot, due to the way React renders elements vs. the way they are directly manipulated with jQuery (e.g. React might "undo" something you've done with jQuery). I'd recommend you stick to just using jQuery without Gatsby/React, until you've got more familiar with React.
Working nicely. Thanks and I'll look more into React!
Newbie here! I'm having problems when doing Gatsby Build. Gatsby Develop went totally fine but on build I get the "WebpackError: Cannot read property 'document' of undefined" error. I'm using jQuery and assume that's the reason why. I understand that I'm supposed to wrap something in the onClientEntry from https://www.gatsbyjs.org/docs/browser-apis/ but I'm still quite confused on how to do that.
In each page that I use jQuery, I import: import $ from .....
and start using jQuery: componentDidMount(){ $(selector).blablabla(); }
It would be really great if someone could give me an example!