Last active
September 11, 2022 11:13
-
-
Save smontlouis/f31cffcb1855bcaa985aba4f0ee091af to your computer and use it in GitHub Desktop.
React Native - Fixed header/footer disappearing on scroll
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { PropTypes, Component } from 'react' | |
import { | |
Animated, | |
ScrollView, | |
Text, | |
View, | |
} from 'react-native' | |
import EStyleSheet from 'react-native-extended-stylesheet' | |
const styles = EStyleSheet.create({ | |
container: { | |
flex: 1, | |
}, | |
scrollView: { | |
padding: 20, | |
}, | |
text: { | |
marginBottom: 60, | |
}, | |
fixedFooter: { | |
backgroundColor: 'blue', | |
position: 'absolute', | |
bottom: 0, | |
left: 0, | |
right: 0, | |
height: 50, | |
} | |
}) | |
export default class BibleViewer extends Component { | |
static propTypes = { | |
} | |
constructor(props) { | |
super(props) | |
this.onScrollMoveFooter = ::this.onScrollMoveFooter | |
} | |
state = { | |
scrollY: new Animated.Value(0), | |
} | |
onScrollMoveFooter(event) { | |
const currentOffset = event.nativeEvent.contentOffset.y | |
const direction = currentOffset > this.offset ? 'down' : 'up' | |
const distance = this.offset ? (this.offset - currentOffset) : 0 | |
const newPosition = this.state.scrollY._value - distance | |
if (currentOffset > 0 && currentOffset < (this.contentHeight - this.scrollViewHeight)) { // Don't react at iOS ScrollView Bounce | |
if (direction === 'down') { | |
if (this.state.scrollY._value < 50) { | |
this.state.scrollY.setValue(newPosition > 50 ? 50 : newPosition) | |
} | |
} | |
if (direction === 'up') { | |
if (this.state.scrollY._value >= 0) { | |
this.state.scrollY.setValue(newPosition < 0 ? 0 : newPosition) | |
} | |
} | |
this.offset = currentOffset | |
} | |
} | |
render() { | |
return ( | |
<View style={styles.container}> | |
<ScrollView | |
onContentSizeChange={(w, h) => { this.contentHeight = h }} | |
onLayout={(ev) => { this.scrollViewHeight = ev.nativeEvent.layout.height }} | |
onScroll={this.onScrollMoveFooter} | |
scrollEventThrottle={16} | |
style={styles.scrollView} | |
> | |
... | |
</ScrollView> | |
<Animated.View | |
style={[ | |
styles.fixedFooter, | |
{ transform: [{ translateY: this.state.scrollY }] }, | |
]} | |
/> | |
</View> | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment