Skip to content

Instantly share code, notes, and snippets.

@jdltechworks
Created January 7, 2019 14:43
Show Gist options
  • Save jdltechworks/0f6d0b0bb4a15e382da0694a96544c6e to your computer and use it in GitHub Desktop.
Save jdltechworks/0f6d0b0bb4a15e382da0694a96544c6e to your computer and use it in GitHub Desktop.
EntriesMultiplier
import React, { Component, Fragment } from "react";
type Props = {
multiplier: number,
setTotal: (total: number) => void,
};
type State = {
isVisible: boolean,
entries: number[] | null,
};
class EntriesMultiplier extends Component<Props, State> {
public state: State = {
isVisible: false,
entries: null,
}
componentDidMount() {
window.addEventListener('resize', this.handleResize);
}
componentWillReceiveProps(nextProps: any) {
if (this.props.multiplier !== nextProps.multiplier) {
this.updateTotal(nextProps.multiplier);
}
}
handleResize = () => {
this.setState({ isVisible: true });
this.fetchDimensions();
}
async fetchDimensions() {
let entries: any = await this.getDimensions();
this.setState({ entries });
this.updateTotal();
}
getDimensions() {
return new Promise((resolve) => setTimeout(() => resolve([
window.innerWidth,
window.innerHeight,
window.outerWidth,
window.outerHeight,
window.screen.width,
]), 1500));
}
updateTotal(multiplier = this.props.multiplier) {
let accumuatedEvenNumbers = 0;
if (this.state.entries) {
for (let i = 0; i < this.state.entries.length; i++) {
if (i % 2 === 0) {
accumuatedEvenNumbers += this.state.entries[i] * multiplier;
}
}
}
this.props.setTotal(accumuatedEvenNumbers);
}
render() {
const { entries, isVisible } = this.state;
if (!isVisible) {
return <div>Resize window to see make component visible!</div>;
}
return (
<Fragment>
<p>
Multiplied entries:
</p>
<ul>
{entries && entries.map((entry, key) => <li key={key}>{ entry * this.props.multiplier }</li>)}
</ul>
<span>Window width = { window.innerWidth }</span>
</Fragment>
);
}
}
export default EntriesMultiplier;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment