Skip to content

Instantly share code, notes, and snippets.

@kkkevinnn
Forked from mmazzarolo/hideOnScroll.js
Last active August 25, 2020 18:19
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save kkkevinnn/25ace65e3df656313990b710354e1541 to your computer and use it in GitHub Desktop.
Save kkkevinnn/25ace65e3df656313990b710354e1541 to your computer and use it in GitHub Desktop.
react-native-action-button hide on scroll
// 1. Define a state variable for showing/hiding the action-button
state = {
isActionButtonVisible: true
}
// 2. Define variables those will keep track of the current scroll position, height and content height
_listViewOffset = 0
_listViewHeight = 0
_listViewContentHeight = 0
// 3. Add an onScroll, onLayout, onContentSizeChange listeners to your listview/scrollview
<ListView
...
onScroll={this._onScroll}
scrollEventThrottle={1}
onContentSizeChange={this._onContentSizeChange}
onLayout={this._onLayout}
...
/>
// 3. Add some logics in the listeners for hiding the action button when scrolling down
_onLayout(e) {
const { height } = e.nativeEvent.layout
this._listViewHeight = height
}
_onContentSizeChange(contentWidth, contentHeight) {
this._listViewContentHeight = contentHeight
}
_onScroll = (event) => {
// Simple fade-in / fade-out animation
const CustomLayoutLinear = {
duration: 100,
create: { type: LayoutAnimation.Types.linear, property: LayoutAnimation.Properties.opacity },
update: { type: LayoutAnimation.Types.linear, property: LayoutAnimation.Properties.opacity },
delete: { type: LayoutAnimation.Types.linear, property: LayoutAnimation.Properties.opacity }
}
// Check if the user is scrolling up or down by confronting the new scroll position with your own one
const limit = this._listViewContentHeight - this._listViewHeight
const offset = event.nativeEvent.contentOffset.y
const currentOffset = (offset > limit) ? limit : offset
const direction = (currentOffset > 0 && currentOffset >= this._listViewOffset)
? 'down'
: 'up'
// If the user is scrolling down (and the action-button is still visible) hide it
const isActionButtonVisible = direction === 'up'
if (isActionButtonVisible !== this.state.isActionButtonVisible) {
LayoutAnimation.configureNext(CustomLayoutLinear)
this.setState({ isActionButtonVisible })
}
// Update your scroll position
this._listViewOffset = currentOffset
}
// 4. In you render show you action-button only if state.isActionButtonVisible === true
<View style={styles.container}>
{yourListView}
{this.state.isActionButtonVisible ? <ActionButton /> : null}
</View>
@yasir-netlinks
Copy link

yasir-netlinks commented May 15, 2018

Hi there, how can I edit this so that when scroll stop for a second or two / when actually scroll stops, the action button should appear !

@marquina-abreu
Copy link

thanks!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment