Skip to content

Instantly share code, notes, and snippets.

@bartimaeus
Created August 15, 2018 17:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bartimaeus/e6f24ef21137ccdc748c1a8d8a5b6c57 to your computer and use it in GitHub Desktop.
Save bartimaeus/e6f24ef21137ccdc748c1a8d8a5b6c57 to your computer and use it in GitHub Desktop.
Lesson 01
import "./index.css";
import React, { Component } from "react";
import subscribeToMessages from "./messages";
import FadeIn from "./FadeIn";
// If user has scrolled up, don't scroll down
class PinScrollToBottom extends Component {
componentDidMount() {
// this.scrollToBottom();
this.scroll();
}
componentDidUpdate(prevProps, prevState, atBottom) {
if (atBottom) {
// this.scrollToBottom();
this.scroll();
}
}
// scrollToBottom() {
// const { userScrolled } = this.props;
// if (!userScrolled) {
// document.documentElement.scrollTop =
// document.documentElement.scrollHeight;
// }
// }
scroll() {
document.documentElement.scrollTop = document.documentElement.scrollHeight;
}
getSnapshotBeforeUpdate() {
const { scrollHeight, scrollTop, clientHeight } = document.documentElement;
const atBottom = scrollHeight === clientHeight + scrollTop;
return atBottom;
}
render() {
return this.props.children;
}
}
class App extends Component {
state = {
messages: [],
userScrolled: false
};
componentDidMount() {
window.addEventListener("scroll", e => this.handleScroll(e));
subscribeToMessages(message => {
this.setState({
messages: this.state.messages.concat([message])
});
});
}
handleScroll = event => {
// const clientHeight = this.app.offsetHeight;
// const scrollHeight = document.documentElement.scrollHeight;
// const scrollTop = document.documentElement.scrollTop;
// // scrollTop + clientHeight < viewHeight;
// console.log("user has scrolled");
// console.log("scrollHeight", scrollHeight);
// console.log(scrollTop);
// console.log(clientHeight);
// console.log(clientHeight + scrollTop);
// if (clientHeight + scrollTop < scrollHeight) {
// this.setState({ userScrolled: true });
// }
};
render() {
const { messages, userScrolled } = this.state;
return (
<div className="app">
<div className="link">
<a href="https://www.youtube.com/watch?v=VKHFZBUTA4k&list=RDVKHFZBUTA4k">
Sketch on YouTube
</a>
</div>
<PinScrollToBottom userScrolled={userScrolled}>
<ol className="messages" ref={node => (this.app = node)}>
{messages.map((message, index) => (
<FadeIn key={index}>
<li className="message">
<div
className="avatar"
style={{ backgroundImage: `url(${message.avatar})` }}
/>
<div className="text">{message.text}</div>
</li>
</FadeIn>
))}
</ol>
</PinScrollToBottom>
</div>
);
}
}
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment