admin管理员组

文章数量:1023738

I am trying to figure out how to implement window.addEventListener in React. I'm developing a website with Gatsby and in "development" environment it works but whenever I start in production it gets an error. This is my code:

const checkHeader = () => { 
    // Detect scroll position
    let viewportWidth = window.innerWidth || document.documentElement.clientWidth;
    if (viewportWidth > 1100) {
        let scrollPosition = Math.round(window.scrollY);

        if (scrollPosition > 100){
            document.querySelector('#nav').classList.add(`${headerStyles.sticky}`);
        }
        else {
            document.querySelector('#nav').classList.remove(`${headerStyles.sticky}`);
        }

    } else {

    }
};

// Run the checkHeader function every time you scroll
window.addEventListener('scroll', checkHeader);

I want to apply a class when Scroll. I've checked that I can't use "window." in React. How is the way to implement this code in React?

I am trying to figure out how to implement window.addEventListener in React. I'm developing a website with Gatsby and in "development" environment it works but whenever I start in production it gets an error. This is my code:

const checkHeader = () => { 
    // Detect scroll position
    let viewportWidth = window.innerWidth || document.documentElement.clientWidth;
    if (viewportWidth > 1100) {
        let scrollPosition = Math.round(window.scrollY);

        if (scrollPosition > 100){
            document.querySelector('#nav').classList.add(`${headerStyles.sticky}`);
        }
        else {
            document.querySelector('#nav').classList.remove(`${headerStyles.sticky}`);
        }

    } else {

    }
};

// Run the checkHeader function every time you scroll
window.addEventListener('scroll', checkHeader);

I want to apply a class when Scroll. I've checked that I can't use "window." in React. How is the way to implement this code in React?

Share Improve this question asked May 9, 2020 at 10:30 JFelixJFelix 1553 silver badges11 bronze badges 4
  • wats the error u get? – Panther Commented May 9, 2020 at 10:32
  • 1 Also if u r using react.. there are chances your applied class suddenly disappears when DOM re-renders. You should modify the state in the eventlistener and set the class based on the state varaible in the rendeer. – Panther Commented May 9, 2020 at 10:33
  • Refer : stackoverflow./questions/38980371/… – Adarsh C Commented May 9, 2020 at 10:43
  • usehooks./useOnScreen - Create an Intersection observer React Hook :) – Oliver Heward Commented May 11, 2020 at 9:10
Add a ment  | 

3 Answers 3

Reset to default 3

During development, react ponents are only run in the browser where window is defined. When building, Gatsby renders these ponents on the server where window is not defined.

Generally with React, the solution is to only access window in ponentDidMount or to check that window exists before accessing it.

const checkHeader = () => { 
    // Detect scroll position
    let viewportWidth = window.innerWidth || document.documentElement.clientWidth;
    if (viewportWidth > 1100) {
        let scrollPosition = Math.round(window.scrollY);

        if (scrollPosition > 100){
            document.querySelector('#nav').classList.add(`${headerStyles.sticky}`);
        }
        else {
            document.querySelector('#nav').classList.remove(`${headerStyles.sticky}`);
        }

    } else {

    }
};

// Check that window exists before accessing it
if (typeof window !== 'undefined') {
    // Run the checkHeader function every time you scroll
    window.addEventListener('scroll', checkHeader);
}

You can directly add window events with Gatsby since it performs server side rendering. To do that you need to add you listeners in gatsby-browser.js inside onClientEntry method which is called when client is loaded

// gatsby-browser.js
// ES6


const checkHeader = () => { 
    // Detect scroll position
    let viewportWidth = window.innerWidth || document.documentElement.clientWidth;
    if (viewportWidth > 1100) {
        let scrollPosition = Math.round(window.scrollY);

        if (scrollPosition > 100){
            document.querySelector('#nav').classList.add(`${headerStyles.sticky}`);
        }
        else {
            document.querySelector('#nav').classList.remove(`${headerStyles.sticky}`);
        }

    } else {

    }
};


export const onClientEntry = () => {
   // Run the checkHeader function every time you scroll
   window.addEventListener('scroll', checkHeader);
}

Calling the function on did mount of the root ponent might solve your issue. for example:

// your entry ponent
const App = () => {

  React.useEffect(() => { // Will be called after mounting the ponnent.
    onClientEntry();
  }, []);

  return (
    <Home />
  );
}

Hope this helps

I am trying to figure out how to implement window.addEventListener in React. I'm developing a website with Gatsby and in "development" environment it works but whenever I start in production it gets an error. This is my code:

const checkHeader = () => { 
    // Detect scroll position
    let viewportWidth = window.innerWidth || document.documentElement.clientWidth;
    if (viewportWidth > 1100) {
        let scrollPosition = Math.round(window.scrollY);

        if (scrollPosition > 100){
            document.querySelector('#nav').classList.add(`${headerStyles.sticky}`);
        }
        else {
            document.querySelector('#nav').classList.remove(`${headerStyles.sticky}`);
        }

    } else {

    }
};

// Run the checkHeader function every time you scroll
window.addEventListener('scroll', checkHeader);

I want to apply a class when Scroll. I've checked that I can't use "window." in React. How is the way to implement this code in React?

I am trying to figure out how to implement window.addEventListener in React. I'm developing a website with Gatsby and in "development" environment it works but whenever I start in production it gets an error. This is my code:

const checkHeader = () => { 
    // Detect scroll position
    let viewportWidth = window.innerWidth || document.documentElement.clientWidth;
    if (viewportWidth > 1100) {
        let scrollPosition = Math.round(window.scrollY);

        if (scrollPosition > 100){
            document.querySelector('#nav').classList.add(`${headerStyles.sticky}`);
        }
        else {
            document.querySelector('#nav').classList.remove(`${headerStyles.sticky}`);
        }

    } else {

    }
};

// Run the checkHeader function every time you scroll
window.addEventListener('scroll', checkHeader);

I want to apply a class when Scroll. I've checked that I can't use "window." in React. How is the way to implement this code in React?

Share Improve this question asked May 9, 2020 at 10:30 JFelixJFelix 1553 silver badges11 bronze badges 4
  • wats the error u get? – Panther Commented May 9, 2020 at 10:32
  • 1 Also if u r using react.. there are chances your applied class suddenly disappears when DOM re-renders. You should modify the state in the eventlistener and set the class based on the state varaible in the rendeer. – Panther Commented May 9, 2020 at 10:33
  • Refer : stackoverflow./questions/38980371/… – Adarsh C Commented May 9, 2020 at 10:43
  • usehooks./useOnScreen - Create an Intersection observer React Hook :) – Oliver Heward Commented May 11, 2020 at 9:10
Add a ment  | 

3 Answers 3

Reset to default 3

During development, react ponents are only run in the browser where window is defined. When building, Gatsby renders these ponents on the server where window is not defined.

Generally with React, the solution is to only access window in ponentDidMount or to check that window exists before accessing it.

const checkHeader = () => { 
    // Detect scroll position
    let viewportWidth = window.innerWidth || document.documentElement.clientWidth;
    if (viewportWidth > 1100) {
        let scrollPosition = Math.round(window.scrollY);

        if (scrollPosition > 100){
            document.querySelector('#nav').classList.add(`${headerStyles.sticky}`);
        }
        else {
            document.querySelector('#nav').classList.remove(`${headerStyles.sticky}`);
        }

    } else {

    }
};

// Check that window exists before accessing it
if (typeof window !== 'undefined') {
    // Run the checkHeader function every time you scroll
    window.addEventListener('scroll', checkHeader);
}

You can directly add window events with Gatsby since it performs server side rendering. To do that you need to add you listeners in gatsby-browser.js inside onClientEntry method which is called when client is loaded

// gatsby-browser.js
// ES6


const checkHeader = () => { 
    // Detect scroll position
    let viewportWidth = window.innerWidth || document.documentElement.clientWidth;
    if (viewportWidth > 1100) {
        let scrollPosition = Math.round(window.scrollY);

        if (scrollPosition > 100){
            document.querySelector('#nav').classList.add(`${headerStyles.sticky}`);
        }
        else {
            document.querySelector('#nav').classList.remove(`${headerStyles.sticky}`);
        }

    } else {

    }
};


export const onClientEntry = () => {
   // Run the checkHeader function every time you scroll
   window.addEventListener('scroll', checkHeader);
}

Calling the function on did mount of the root ponent might solve your issue. for example:

// your entry ponent
const App = () => {

  React.useEffect(() => { // Will be called after mounting the ponnent.
    onClientEntry();
  }, []);

  return (
    <Home />
  );
}

Hope this helps

本文标签: javascriptHow to windowaddEventListener in React JSStack Overflow