Last active
November 16, 2018 01:31
-
-
Save hypervillain/28cfe17c64fdc7b3f7866bb77316c6bb to your computer and use it in GitHub Desktop.
A generic React component that calculates and forwards the distance between mouse position and element
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 { Component } from 'react'; | |
import { func } from 'prop-types'; | |
// See related Gist | |
import MousePosListener from '../MousePosListener'; | |
const distancePoints = (x1, y1, x2, y2) => | |
Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)); | |
class ForwardProximity extends Component { | |
static propTypes = { | |
children: func.isRequired, | |
} | |
constructor(props) { | |
super(props); | |
this.state = {}; | |
} | |
getProximity = (mousepos) => { | |
if (!this.state.ref) { | |
return; | |
} | |
const docScrolls = { | |
left: document.body.scrollLeft + document.documentElement.scrollLeft, | |
top: document.body.scrollTop + document.documentElement.scrollTop, | |
}; | |
const elRect = this.state.ref.getBoundingClientRect(); | |
const elCoords = { | |
x1: elRect.left + docScrolls.left, | |
x2: elRect.width + elRect.left + docScrolls.left, | |
y1: elRect.top + docScrolls.top, | |
y2: elRect.height + elRect.top + docScrolls.top, | |
}; | |
const closestPoint = { | |
x: mousepos.x, | |
y: mousepos.y, | |
}; | |
if (mousepos.x < elCoords.x1) { | |
closestPoint.x = elCoords.x1; | |
} else if (mousepos.x > elCoords.x2) { | |
closestPoint.x = elCoords.x2; | |
} | |
if (mousepos.y < elCoords.y1) { | |
closestPoint.y = elCoords.y1; | |
} else if (mousepos.y > elCoords.y2) { | |
closestPoint.y = elCoords.y2; | |
} | |
this.setState({ | |
proximity: distancePoints(mousepos.x, mousepos.y, closestPoint.x, closestPoint.y), | |
}); | |
} | |
// This is deprecated. | |
// Will be updated when hooks | |
// get out of RFC | |
ref = (ref) => { | |
if (!this.state.ref && ref) { | |
this.setState({ | |
ref, | |
}); | |
} | |
} | |
render() { | |
return ( | |
<MousePosListener | |
onMouseMoved={this.getProximity} | |
> | |
{this.props.children({ ref: this.ref, proximity: this.state.proximity })} | |
</MousePosListener> | |
); | |
} | |
} | |
ForwardProximity.displayName = 'ForwardProximity'; | |
export default ForwardProximity; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment