Created
August 27, 2024 12:09
-
-
Save tonkec/0bf19b100fa446a656afdaa78e6417bc to your computer and use it in GitHub Desktop.
toggling-audio-in-react-without-re-rendering-component
This file contains hidden or 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
| import React, { useRef, useEffect } from 'react'; | |
| import p5 from 'p5'; | |
| function Game() { | |
| const audioRef = useRef(new Audio('/path/to/your/audio/file.mp3')); | |
| let audioButton; | |
| useEffect(() => { | |
| // Using p5.js to create the audio toggle button | |
| const sketch = (p) => { | |
| p.setup = () => { | |
| p.createCanvas(400, 400); | |
| audioButton = p.createImg(audioRef.current.paused ? '/path/to/audioOff.png' : '/path/to/audioOn.png', "audio button"); | |
| audioButton.position(20, p.height - 50); | |
| audioButton.size(30, 30); | |
| audioButton.mouseClicked(() => { | |
| if (audioRef.current.paused) { | |
| audioRef.current.play(); | |
| } else { | |
| audioRef.current.pause(); | |
| } | |
| // Update button icon without causing a re-render | |
| audioButton.elt.src = audioRef.current.paused ? '/path/to/audioOff.png' : '/path/to/audioOn.png'; | |
| }); | |
| }; | |
| p.draw = () => { | |
| // Game drawing logic... | |
| }; | |
| }; | |
| new p5(sketch); | |
| return () => { | |
| audioRef.current.pause(); // Ensure the audio is paused if component unmounts | |
| }; | |
| }, []); | |
| // No state updates, so no risk of resetting score/timer | |
| return ( | |
| <div> | |
| {/* The canvas will be rendered by p5.js */} | |
| </div> | |
| ); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment