Skip to content

Instantly share code, notes, and snippets.

@Emuentes
Last active October 20, 2017 16:40
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 Emuentes/bc37d360f2c3351cdffc612ed0659b25 to your computer and use it in GitHub Desktop.
Save Emuentes/bc37d360f2c3351cdffc612ed0659b25 to your computer and use it in GitHub Desktop.
// Playing around with the Higher Order Components exercise from the React-Training github!
// https://github.com/ReactTraining/react-workshop/tree/master/subjects/HigherOrderComponents
// FUN FUN FUN!!!
import React from 'react'
import ReactDOM from 'react-dom'
import PropTypes from 'prop-types'
import * as styles from './styles'
const withMouse = (Component) => {
let mouseTimeout;
return class ComponentWithMouse extends React.Component {
state = {
mouse: {
x: 0,
y: 0,
isMoving: false
},
cat: {
x: 0, y: 0
},
};
handleMouseMove = (event) => {
if (mouseTimeout) { clearTimeout(mouseTimeout) }
const {
x: previousClientX,
y: previousClientY,
} = this.state.mouse;
const {
clientX,
clientY
} = event;
this.setState({
mouse: {
x: clientX,
y: clientY,
isMoving: true
}
});
var catTimeout = setTimeout(() => {
this.setState({
cat: {
x: clientX,
y: clientY,
shouldRunRight: previousClientX && previousClientX < clientX
}
})
clearTimeout(catTimeout);
}, 150)
mouseTimeout = setTimeout(() => {
console.log('not a creatue (other than a cat) was stirring!');
this.setState({
mouse: {
x: clientX,
y: clientY,
isMoving: false
}
});
clearTimeout(mouseTimeout);
}, 150)
}
render() {
return (
<div onMouseMove={this.handleMouseMove}>
<Component {...this.props} mouse={this.state.mouse} cat={this.state.cat}/>
</div>
)
}
}
}
class App extends React.Component {
static propTypes = {
mouse: PropTypes.shape({
x: PropTypes.number.isRequired,
y: PropTypes.number.isRequired
}).isRequired
}
render() {
const { mouse, cat } = this.props
const catCaughtMouse =
cat.x === mouse.x &&
cat.y === mouse.y;
return (
<div style={Object.assign({},
styles.container, {
cursor: (
catCaughtMouse ?
`url(http://www.rw-designer.com/cursor-view/36921.gif), auto` :
styles.container.cursor
)
})}>
{mouse ? (
<h1>The mouse position is ({mouse.x}, {mouse.y})</h1>
) : (
<h1>We don't know the mouse position yet :(</h1>
)}
{cat.x === 0 && cat.y === 0 ? (
<h1>GET THE MOUSE!</h1>
) : (
<h1>Mouse is {mouse.isMoving ? 'getting away!' : 'OUT OF LUCK!'}</h1>
)
}
<div
className="cat-img"
style={{
left: cat.x,
top: cat.y,
backgroundImage: catCaughtMouse ? '' : `url(http://www.rw-designer.com/cursor-view/${ mouse.isMoving ? '36925' : '36920'}.gif)`,
transform: `scaleX(${cat.shouldRunRight ? -1 : 1})`,
height: 48,
width: 48,
position: 'absolute'
}}
></div>
</div>
)
}
}
const AppWithMouse = withMouse(App)
ReactDOM.render(<AppWithMouse/>, document.getElementById('app'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment