Skip to content

Instantly share code, notes, and snippets.

@MiguelSavignano
Created January 26, 2017 16:44
Show Gist options
  • Save MiguelSavignano/cb8457d78b3f498594133d38ce50b757 to your computer and use it in GitHub Desktop.
Save MiguelSavignano/cb8457d78b3f498594133d38ce50b757 to your computer and use it in GitHub Desktop.
import React, { PropTypes } from 'react'
import ReactOnRails from 'react-on-rails'
import {Api} from '../../app'
export class PaginateMore extends React.Component {
constructor(props) {
super(props)
const current_page = this.props.current_page || 1
this.offset = this.props.offset || 0.8
this.state ={
current_page: current_page,
next_page: current_page + 1
}
}
componentWillMount(){
$(window).scroll(this.scrollHandler);
}
componentWillUnmount(){
$(window).off("scroll", this.scrollHandler);
}
scrollHandler = () => {
var offset = (this.totalPageHeigth() * this.offset ) // 673.6
if( this.currentPageHeigth() > offset ){
this.scrollUnsubscribe()
this.managerGetMore( () => {
this.scrollSubscribe()
})
}
}
scrollSubscribe = () => {
$(window).scroll(this.scrollHandler);
}
scrollUnsubscribe = () => {
$(window).off("scroll", this.scrollHandler);
}
currentPageHeigth(){
return Math.round($(window).scrollTop() + $(window).height() )
}
totalPageHeigth(){
return $(document).height()
}
managerGetMore = (callback) => {
if(!this.state.next_page ) return false
this.getMoreDataHtml( (html) => {
if(callback){ callback() }
if(!html){
this.setState({ next_page: undefined })
}else{ this.onMore(html) }
})
}
getMoreDataHtml(callback){
Api.get(this.props.url, {page:this.state.next_page}, (result) => {
if (result.count != 0) callback(result.html)
else callback(undefined)
})
}
onMore = (html) => {
const container = this.props.container || ".react-infinite-scroll"
$(container).append(html)
ReactOnRails.reactOnRailsPageLoaded() // refresh react component from the ajax
this.setState({ next_page: this.state.next_page + 1 })
}
onClickHandler = () => {
this.managerGetMore()
}
render() {
return (
<div></div>
)
}
}
// <a onClick={this.onClickHandler} className="more">More</a>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment