Created
August 14, 2020 17:25
-
-
Save abelsan/78f96d7c52ffa2295b7e97b284b2b61f to your computer and use it in GitHub Desktop.
Clock using react
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
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="UTF-8" /> | |
<title>Clock</title> | |
<!-- don't use this in production: --> | |
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script> | |
</head> | |
<body> | |
<!-- note difference in style properties from react --> | |
<h1 style="font-family: Arial;">Clock</h1> | |
<!-- target div --> | |
<div id="root"></div> | |
<!-- load react --> | |
<script | |
src="https://unpkg.com/react/umd/react.development.js" | |
crossorigin | |
></script> | |
<script | |
src="https://unpkg.com/react-dom/umd/react-dom.development.js" | |
crossorigin | |
></script> | |
<!-- Load our React component. --> | |
<script src="clock.js" defer type="text/babel"></script> | |
</body> | |
</html> |
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
// clock component | |
const Clock = (props) => { | |
// keep track of time/counter | |
const [time, setTime] = React.useState(new Date().toLocaleTimeString()); | |
const [counter, setCounter] = React.useState(0); | |
function updateTime(){ | |
const date = new Date() | |
setTime(date.toLocaleTimeString()); | |
} | |
function updateCounter(){ | |
setCounter(counter + 1); | |
console.log('counter: ' + counter); | |
} | |
// update time/counter | |
React.useEffect(() => { | |
// fire in one second - compare to interval | |
const timeout = setTimeout(() => { | |
updateCounter(); // note order | |
updateTime(); | |
}, 1000); | |
// cleanup | |
return () => { | |
clearTimeout(timeout); | |
} | |
}, [time]); | |
// note difference in style properties from html | |
return ( | |
<div style={{ fontFamily: 'Arial', fontSize: '10em', color: 'green' }}> | |
<div>{time}</div> | |
</div> | |
) | |
} | |
ReactDOM.render( | |
<Clock/>, | |
document.getElementById('root') | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment