Created
November 13, 2019 11:50
-
-
Save juhahinkula/99df5f8cb2f0566318a929b5dfb762b8 to your computer and use it in GitHub Desktop.
Counter using useReducer
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
<!-- Fetch astronomy picture of the day from NASA API --> | |
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="utf-8" /> | |
<title>React example</title> | |
</head> | |
<body> | |
<!-- Root container for react components --> | |
<div id="root"></div> | |
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script> | |
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script> | |
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.26.0/babel.min.js"></script> | |
<script type="text/babel"> | |
function reducer(state, action) { | |
switch (action.type) { | |
case 'increment': | |
return {count: state.count + 1}; | |
case 'decrement': | |
return {count: state.count - 1}; | |
default: | |
throw new Error(); | |
} | |
} | |
function ReducerCounter() { | |
const [state, dispatch] = React.useReducer(reducer, {count: 0}); | |
return ( | |
<div> | |
Count: {state.count} | |
<br /> | |
<button onClick={() => dispatch({type: 'decrement'})}>-</button> | |
<button onClick={() => dispatch({type: 'increment'})}>+</button> | |
</div> | |
); | |
} | |
ReactDOM.render(<ReducerCounter />, document.getElementById("root")); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment