Created
January 7, 2019 14:43
-
-
Save jdltechworks/0f6d0b0bb4a15e382da0694a96544c6e to your computer and use it in GitHub Desktop.
EntriesMultiplier
This file contains hidden or 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, { 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