Skip to content

Instantly share code, notes, and snippets.

@insin
Last active May 30, 2023 19:49
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save insin/e523519243a1db6a1fdf66f31d6ab62a to your computer and use it in GitHub Desktop.
Save insin/e523519243a1db6a1fdf66f31d6ab62a to your computer and use it in GitHub Desktop.
Using CSS transition & transform to move a component: https://react-simple-transform.surge.sh
import React from 'react'
import {render} from 'react-dom'
let Board = React.createClass({
getInitialState() {
return {
x: 150,
y: 150,
}
},
componentDidMount() {
setInterval(() => {
this.setState({
x: 32 + Math.floor(246 * Math.random()),
y: 32 + Math.floor(246 * Math.random()),
})
}, 1000)
},
render() {
let {x, y} = this.state
return <div style={{
border: '1px solid black',
height: 300,
position: 'relative',
width: 300,
}}>
<div
children={'\u2663'}
style={{
left: 0,
fontSize: '32px',
position: 'absolute',
top: 0,
transform: `translateX(${x}px) translateY(${y}px)`,
transition: 'transform .5s',
}}
/>
</div>
}
})
render(<Board/>, document.getElementById('app'))
import {h, Component} from 'preact'
class Board extends Component {
state = {
x: 150,
y: 150,
}
componentDidMount() {
this.interval = setInterval(() => {
this.setState({
x: 32 + Math.floor(246 * Math.random()),
y: 32 + Math.floor(246 * Math.random()),
})
}, 1000)
}
componentWillUnmount() {
console.log('unmounting')
clearInterval(this.interval)
}
render({}, {x, y}) {
return <div style={{
border: '1px solid black',
height: 300,
position: 'relative',
width: 300,
}}>
<div
children={'\u2663'}
style={{
left: 0,
fontSize: '32px',
position: 'absolute',
top: 0,
transform: `translateX(${x}px) translateY(${y}px)`,
transition: 'transform .5s',
}}
/>
</div>
}
}
export default Board
@harsha-nn
Copy link

Nice work

@loverdeveloper
Copy link

TNX

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment