Skip to content

Instantly share code, notes, and snippets.

@DroopyTersen
Last active February 19, 2019 16:41
Show Gist options
  • Save DroopyTersen/93313a1d8d9f418cd258f943ef960ad1 to your computer and use it in GitHub Desktop.
Save DroopyTersen/93313a1d8d9f418cd258f943ef960ad1 to your computer and use it in GitHub Desktop.
Composing Behavior with React hooks - Class Component baseline
import React from "react";
export default class NotificationBanner extends React.Component {
intervalId = null;
state = {
notifications: [],
isLoading: true,
currentPage: 1
};
componentDidMount() {
this.setState({ notifications: NOTIFICATIONS_DATA, isLoading: false });
this.startAutoPaging();
}
componentWillUnmount() {
this.stopAutoPaging();
}
startAutoPaging = () => {
this.stopAutoPaging();
this.intervalId = setInterval(this.goForward, 2000);
};
stopAutoPaging = () => {
if (this.intervalId) clearInterval(this.intervalId);
};
goBack = () => {
let newPage = this.state.currentPage - 1;
if (newPage < 1) newPage = this.state.notifications.length;
this.setState({ currentPage: newPage });
};
goForward = () => {
let newPage = this.state.currentPage + 1;
if (newPage > this.state.notifications.length) newPage = 1;
this.setState({ currentPage: newPage });
};
handleMouseEnter = () => {
this.stopAutoPaging();
};
handleMouseLeave = () => {
this.startAutoPaging();
};
render() {
let activeItem: Notification = this.state.notifications.length
? this.state.notifications[this.state.currentPage - 1]
: {};
return (
<div
className="notifications"
onMouseEnter={this.handleMouseEnter}
onMouseLeave={this.handleMouseLeave}
>
<button onClick={this.goBack}>Prev</button>
<div className="active-item">{activeItem.title}</div>
<button onClick={this.goForward}>Next</button>
</div>
);
}
}
const NOTIFICATIONS_DATA = [
{ title: "React hooks change the way we write components." },
{ title: "useState puts state in Function Components" },
{ title: "useEffect handles your component lifecycle needs" }
];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment