Last active
July 15, 2016 18:16
-
-
Save markrickert/f57986b8dfd80f0a68969a001e5681fa to your computer and use it in GitHub Desktop.
Scrolling to the bottom of a React Native ScrollView or ListView
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 } from 'react' | |
import {View, ListView, Text } from 'react-native' | |
export default class ScrollToBottomExample extends React.Component { | |
constructor (props) { | |
super(props) | |
// Set up our two placeholder values. | |
this.listHeight = 0 | |
this.footerY = 0 | |
const data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] | |
let ds = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 }) | |
this.state = { | |
dataSource: ds.cloneWithRows(data) | |
} | |
} | |
componentDidMount () { | |
this.scrollToBottom() | |
} | |
// The magical function! 🎉 | |
scrollToBottom(animated = true) { | |
if (this.listHeight && this.footerY && this.footerY > this.listHeight) { | |
// Calculates the y scroll position inside the ListView | |
const scrollTo = this.footerY - this.listHeight | |
// Scroll that sucker! | |
this.refs.listView.scrollTo({ | |
y: scrollTo, | |
animated: animated, | |
}) | |
} | |
} | |
customRowRender = (rowData, sectionId, rowId) => { | |
return ( | |
<View style={{height: 100}}> | |
<Text>{rowData}</Text> | |
</View> | |
) | |
} | |
// Save the list's height when it renders | |
onLayout = (event) => { | |
const layout = event.nativeEvent.layout | |
this.listHeight = layout.height | |
} | |
// Render a fake footer | |
renderFooter = () => { | |
return ( | |
<View onLayout={this.onFooterLayout} /> | |
) | |
} | |
// When the fake footer is laid out, store the y-position | |
onFooterLayout = (event) => { | |
const layout = event.nativeEvent.layout | |
this.footerY = layout.y | |
} | |
render () { | |
return ( | |
<ListView | |
ref='listView' | |
dataSource={this.state.dataSource} | |
onLayout={this.onLayout} | |
renderFooter={this.renderFooter} | |
renderRow={this.customRowRender} | |
enableEmptySections /> | |
) | |
} | |
} | |
export default ScrollToBottomExample |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment