Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add class in element on scroll React js

Tags:

reactjs

How to add class in element on scroll React js, I want to add class in on scroll and remove that class if on top of the page.

import React from "react"
import { Link } from "react-router"
import { prefixLink } from "gatsby-helpers"
import Helmet from "react-helmet"
import { config } from "config"

module.exports = React.createClass({
  propTypes() {
    return {
      children: React.PropTypes.any,
    }
  },
  render() {
  window.addEventListener('scroll', (event) => {

    });
    return (
      <div>
        <header className="header">
          <div className="top-bar">
            <span><a href="tel:6788272782">678-827-2782 </a></span>
            <span><a href="mailto:[email protected]"> [email protected]</a></span>
            <button>Login</button>
          </div>
        </header>
        {this.props.children}
      </div>
    )
  },

})
like image 265
harry Avatar asked May 26 '17 15:05

harry


People also ask

How do you add or remove class on scroll in React JS?

To toggle class based on scroll position with React, we can listen to the scroll event on the scroll container element. to define the useScrollHandler hook to watch the scroll event on the document . We have the scroll state that's set to true if we scroll more than 10 pixels down the page.


1 Answers

If you want to use React Hooks in 2020 stateless component

const [scroll, setScroll] = useState(false);
 useEffect(() => {
   window.addEventListener("scroll", () => {
     setScroll(window.scrollY > 50);
   });
 }, []);

and use it anywhere in your code

className={scroll ? "bg-black" : "bg-white"}

setScroll(window.scrollY > 50); here 50 specify the height.

like image 113
ZiaUllahZia Avatar answered Oct 01 '22 10:10

ZiaUllahZia