I've created a React component for a fixed nav that I would like to remain hidden, until I scroll past a certain point on the page, then slides into view. Medium has a header similar to what I'm describing.
This is a relatively trivial task in jQuery, with scrollmagic or waypoints but is there an idiomatic way of accomplishing this with React and vanilla JS?
By using useRef () in a React component, we have an entry to the underlaying HTML element. This gives us full access to all of the powerful DOM APIs. Now that we have seen how we can scroll to an element by using a reference. We can utilize that same method to scroll to a React component.
The "scroll-to-top" feature is an excellent addition to any website that forces visitors to scroll a long distance before reaching the bottom of the page, since it becomes quite annoying to return back to the top. In this hands-on guide, we will learn how to make a React button that allows users to "scroll to the top."
Introduction React Revealis an animation framework for React. It's MIT licensed, has a tiny footprint and written specifically for React in ES6. It can be used to create various cool reveal on scroll animations in your application. If you liked this package, don't forget to star the Github repository.
There are many libraries that specialize in scroll animations. A popular is aos at about 4.5kb, and another one is sal.js, which is under 1kb. On the other hand, react-visibility-sensor is about 2.9kb, and react-spring is around 10kb.
React Way with vanilla JS jsfiddle;
don't forget to remove EventListener. In this example component will render if only it is neccessary
class TopBar extends React.Component {
state = { isHide: false };
hideBar = () => {
const { isHide } = this.state
window.scrollY > this.prev ?
!isHide && this.setState({ isHide: true })
:
isHide && this.setState({ isHide: false });
this.prev = window.scrollY;
}
componentDidMount(){
window.addEventListener('scroll', this.hideBar);
}
componentWillUnmount(){
window.removeEventListener('scroll', this.hideBar);
}
render(){
const classHide = this.state.isHide ? 'hide' : '';
return <div className={`topbar ${classHide}`}>topbar</div>;
}
}
You could use a component such as react-headroom to do the heavy lifting for you. Or, you can still use waypoints in React, setting it up in the componentDidMount
lifecycle method and removing it using componentWillUnmount
.
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