Advertisement
Guest User

Untitled

a guest
Apr 23rd, 2019
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.83 KB | None | 0 0
  1. const initializeState = () => ({
  2. width: 100
  3. })
  4.  
  5. // ✅ note how the value returned from the fn above overrides initialState below:
  6. const initialState = { width: 15 }
  7. const reducer = (state, action) => {
  8. switch (action) {
  9. case 'plus':
  10. return { width: state.width + 15 }
  11. case 'minus':
  12. return { width: Math.max(state.width - 15, 2) }
  13. default:
  14. throw new Error("what's going on?" )
  15. }
  16. }
  17.  
  18. const Bar = () => {
  19. const [state, dispatch] = useReducer(reducer, initialState, initializeState)
  20. return <>
  21. <div style={{ background: 'teal', height: '30px', width: state.width }}></div>
  22. <div style={{marginTop: '3rem'}}>
  23. <button onClick={() => dispatch('plus')}>Increase bar size</button>
  24. <button onClick={() => dispatch('minus')}>Decrease bar size</button>
  25. </div>
  26. </>
  27. }
  28.  
  29. ReactDOM.render(Bar)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement