Last active
November 13, 2018 13:46
-
-
Save rajivnarayana/6aa28f31be2d255d2d4b44b94890f61a to your computer and use it in GitHub Desktop.
Inline React component that shows animated counter updates using React Hooks.
This file contains 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
<head> | |
<script src="https://unpkg.com/[email protected]/umd/react.production.min.js" crossorigin></script> | |
<script src="https://unpkg.com/[email protected]/umd/react-dom.production.min.js" crossorigin></script> | |
<script src="https://unpkg.com/[email protected]/babel.min.js" crossorigin></script> | |
<style> | |
span.gone { | |
color : transparent; | |
transition: color 0.3s; | |
-webkit-transition: color 0.3s; | |
} | |
span.visible { | |
transition: color 0.3s; | |
-webkit-transition: color 0.3s; | |
color : black; | |
} | |
</style> | |
</head> | |
<body> | |
<script type="text/babel"> | |
const useEffect = React.useEffect; | |
const useState = React.useState; | |
const useRef = React.useRef; | |
const TIMEOUT = 300;//ms | |
const useAnimateChanges = (value, spanEl) => useEffect(() => { | |
setTimeout( _=> spanEl.current.className = "visible",TIMEOUT) | |
return () => { | |
spanEl.current.className = "gone"; | |
} | |
}, [value]); | |
function Digit({value}) { | |
const spanEl = useRef(null); | |
const [digit, setDigit] = useState(null); | |
setTimeout(_ => setDigit(value), TIMEOUT); | |
useAnimateChanges(value, spanEl); | |
return <span ref={spanEl}>{digit}</span> | |
} | |
function Clicker() { | |
const [count, setCount] = useState(0); | |
return <div>You clicked {count} times. | |
<div style={{fontSize : 400}}> | |
{new String(count).split("").map((v, index, arr) => <Digit key={arr.length-index-1} value={v} />)} | |
</div> | |
<button onClick={_=>setCount(count+1)}>Click Me!</button> | |
</div> | |
} | |
ReactDOM.render(<div><Clicker/></div> | |
, document.getElementById('container')); | |
</script> | |
<div id="container"> | |
</div> | |
<!-- <div id="text"> | |
<span id="counter" style="font-size : 300px">0</span> | |
</div> | |
<button onclick="flash()">Flash Me!</button> | |
<script> | |
let counter = 0 | |
function flash() { | |
const text = document.getElementById("counter"); | |
text.className = "gone"; | |
setTimeout(_ => text.innerHTML = ""+ (++counter), 300); | |
setTimeout(_ => text.className = "visible", 600); | |
; | |
} | |
</script> --> | |
</body> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment