React-run-away-button
On mouse hover the button runs away from the mouse pointer
by sendil J
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react-dom.min.js"></script>
<script src="https://unpkg.com/[email protected]/prop-types.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/foundation/6.3.0/css/foundation.min.css">
<div id="app"></div>
SCSS
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
#app {
background: #fff;
border-radius: 4px;
padding: 20px;
transition: all 0.2s;
height: 100vh;
}
h2 {
font-weight: bold;
margin-bottom: 15px;
}
.stage {
font-weight: 300;
font-family: Helvetica, Arial, sans-serif;
position: relative
}
.RunawayBtn {
transition:0.25s ease-out all;
position: absolute;
width: 125px;
height: 50px;
background: #333;
display: table;
font-size: 1.5rem;
span {
color: #fff;
display: table-cell;
vertical-align: middle;
text-align: center
}
}
Babel + JSX
const getRandomPoint = (elementWidth, elementHeight) => {
let x = (Math.random() * (window.innerWidth - elementWidth)).toFixed()
let y = (Math.random() * (window.innerHeight - elementHeight)).toFixed()
return {
x: x + 'px',
y: y + 'px'
}
}
class RunawayButton extends React.Component {
constructor(props) {
super(props)
this.jump = this.jump.bind(this)
this.state = {
style: {
position:'absolute',
top: 'calc(50vh - 50px/2)',
left: 'calc(50vw - 175px/2)',
}
}
}
jump(event) {
let point = getRandomPoint(125, 50);
this.setState({
style: {
top: point.y,
left: point.x
}
});
}
render() {
return (
<button className="RunawayBtn" onMouseEnter={ this.jump } style={ this.state.style }> <span>{ this.props.title }</span></button>
)
}
}
RunawayButton.propTypes = {
title: React.PropTypes.string.isRequired
}
class App extends React.Component {
constructor(props) {
super(props)
}
render() {
return (
<div className="stage">
<h2>Try Your luck, to catch the button..</h2>
<RunawayButton title="Catch me!" />
</div>
)
}
}
ReactDOM.render(<App />, document.querySelector("#app"))