javascript - How to window.addEventListener in React JS - Stack Overflow

I am trying to figure out how to implement window.addEventListener in React. I'm developing a webs

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745593313a4634960.html

相关推荐

  • javascript - How to window.addEventListener in React JS - Stack Overflow

    I am trying to figure out how to implement window.addEventListener in React. I'm developing a webs

    7小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信