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>
)
},
})
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With