On this page
article
React
UseRef
To reference an existing element you can use this setup
inputRef = useRef(null)
return (
<>
<div ref={inputRef}></div>
<div onClick=() => inputRef.current.focus()></div>
</>
)
Setup
Convert Existing Project to TypeScript
Add Basics
| Name | Description | Package |
|---|---|---|
| Router | Routing | react-router-dom |
| Zustand | State Management (Top → Down) | zustand |
| Medusa | E-Commerce with server | medusa-react @tanstack/react-query @medusajs/medusa |
yarn add react-router-dom zustand medusa-react @tanstack/react-query @medusajs/medusa
# OR
yarn add react-router-dom zustand
yarn add medusa-react @tanstack/react-query @medusajs/medusa
Intercept MediaSession (keyboard shortcut for Play Pause)
ref
navigator.mediaSession.setActionHandler('pause', () => buttonRef.current?.click());
navigator.mediaSession.setActionHandler('play', () => buttonRef.current?.click());
It doesn’t use React state, so you need to simulate a button click that will update the state (using useRef)
const buttonRef = useRef<HTMLButtonElement | null>(null)
return (
<button ref={buttonRef} onClick={handleGlobalPlay} className={"mx-auto"}>
)
const handleGlobalPlay = () => {
audio.map(el => {
const audioId = generateUniqueName(`${el.title}AudioRef`)
const playConfig = generateUniqueName(`${el.title} playing`)
const isPlaying = Boolean(Number(searchParams.get(playConfig)) || false)
const audioEl: HTMLAudioElement | null = document.getElementById(audioId) as HTMLAudioElement
// console.log(`audioId=${audioId} playConfig=${playConfig} isPlaying=${isPlaying}`)
!globalPlay && isPlaying ? audioEl.play() : audioEl.pause()
})
setGlobalPlay(!globalPlay)
}
const buttonRef = useRef<HTMLButtonElement | null>(null)
useEffect(() => {
navigator.mediaSession.setActionHandler('pause', () => buttonRef.current?.click());
navigator.mediaSession.setActionHandler('play', () => buttonRef.current?.click());
}, []);