|
| 1 | +import {React, ReactDOM} from './react.js'; |
| 2 | +import {createComponent} from '@lit-labs/react'; |
| 3 | +import {FlyingTriangles as FlyingTrianglesWC} from './flying-triangles.js'; |
| 4 | + |
| 5 | +/* |
| 6 | + The <flying-triangles> component is stateful and uncontrolled. |
| 7 | +
|
| 8 | + A stateful component maintains state independent of React. |
| 9 | + Meaning component state must be reconciled with React state. |
| 10 | + This is usually accomplished through refs and callbacks. |
| 11 | + |
| 12 | + <flying-triangles> will dispatch a 'playing-change' event when |
| 13 | + component state changes. |
| 14 | + |
| 15 | + The 'playing-change' provides React an opportunity to update |
| 16 | + UI data based on the properties and attributes of |
| 17 | + a <flying-triangles> component. |
| 18 | +*/ |
| 19 | + |
| 20 | +const { useRef, useState, useCallback } = React; |
| 21 | + |
| 22 | +const FlyingTriangles = createComponent( |
| 23 | + React, |
| 24 | + 'flying-triangles', |
| 25 | + FlyingTrianglesWC, |
| 26 | + {onPlayingChange: 'playing-change'}, |
| 27 | +); |
| 28 | + |
| 29 | +export const App = () => { |
| 30 | + const ref = useRef(null); |
| 31 | + const [isPlaying, setIsPlaying] = useState(false); |
| 32 | + |
| 33 | + // Listen for playing-change events |
| 34 | + const onPlayingChange = useCallback(() => { |
| 35 | + setIsPlaying(ref.current?.isPlaying); |
| 36 | + }, []); |
| 37 | + |
| 38 | + // UI callbacks |
| 39 | + const onPlay = useCallback(() => ref.current?.play(), []); |
| 40 | + const onPause = useCallback(() => ref.current?.pause(), []); |
| 41 | + |
| 42 | + return ( |
| 43 | + <> |
| 44 | + <FlyingTriangles |
| 45 | + ref={ref} |
| 46 | + onPlayingChange={onPlayingChange}> |
| 47 | + </FlyingTriangles> |
| 48 | + <button disabled={isPlaying} onClick={onPlay}> |
| 49 | + play |
| 50 | + </button> |
| 51 | + <button disabled={!isPlaying} onClick={onPause}> |
| 52 | + pause |
| 53 | + </button> |
| 54 | + </> |
| 55 | + ); |
| 56 | +}; |
| 57 | + |
| 58 | +const node = document.querySelector('#app'); |
| 59 | +const root = ReactDOM.createRoot(node!); |
| 60 | + |
| 61 | +root.render(<App></App>); |
0 commit comments