1

I want to when scroll down 100px , add body className="showdiv" on gatsby react.

How can I do this?

I try this code:

state = {
  isTop: true,
};

componentDidMount() {
  document.addEventListener('scroll', () => {
    const isTop = window.scrollY < 100;
    if (isTop !== this.state.isTop) {
        this.setState({ isTop })
    }
  });
}

classname

{this.state.isTop ? 'down' : 'up'}

But I can't add body class. I want to new and simple idea..

Thanks

brooksrelyt
  • 3,925
  • 5
  • 31
  • 54
cnsvnc
  • 714
  • 6
  • 16
  • Have you tried `window.addEventListener('scroll'` instead? – Tholle Jul 12 '18 at 00:24
  • i dont know im new , just i want to when i scroll down 100px , add body classname just this. @Tholle – cnsvnc Jul 12 '18 at 00:25
  • See https://stackoverflow.com/a/17457651/5079258 – Alan Friedman Jul 12 '18 at 00:28
  • @AlanFriedman thanks for answer , how can i use this code in react ? javascript is ok but i cant work on react. u can answer reactjs code my question ? – cnsvnc Jul 12 '18 at 00:30
  • Sure you can use it in React. Since `body` is outside of your React root, you'll need to use imperative JS to set the class. – Alan Friedman Jul 12 '18 at 00:32
  • @Tholle just i tried this code but i dont want this use. i want to just when user scroll down 100px, add body class "showChildDiv" just this. – cnsvnc Jul 12 '18 at 00:34
  • @Tholle 'body' is outside React root i cant change className, i need a simple code. – cnsvnc Jul 12 '18 at 00:36

1 Answers1

2

You can add a scroll listener like you've done, but instead add/remove the showChildDiv class from the body depending on the scroll position.

Example

class App extends React.Component {
  componentDidMount() {
    window.addEventListener("scroll", this.toggleBodyClass);
    this.toggleBodyClass();
  }

  componentWillUnmount() {
    window.removeEventListener("scroll", this.toggleBodyClass);
  }

  toggleBodyClass = () => {
    if (window.scrollY < 100) {
      document.body.classList.add("showChildDiv");
    } else {
      document.body.classList.remove("showChildDiv");
    }
  };

  render() {
    return (
      <div
        style={{
          height: "1000px"
        }}
      />
    );
  }
}
Tholle
  • 108,070
  • 19
  • 198
  • 189