I was creating this React component and I was astonished by the fact that when I clicked on the video I got false on console immediatelly after the video started. I was expecting that it would print true when the video started, and false when it finished. I think I'm confusing the lifecycle of this particular component, and I would be really grateful if someone could clarify this to me.
const Video = ({src, type, index, isAutoPlay}) => {
const [play, setPlay] = useState(isAutoPlay)
const playRef = useRef();
useEffect(() => {
if (play && playRef.current) {
playRef.current.play();
}
return () => setPlay(false)
}, [play]);
return (
<>
<video
className="slide"
ref={playRef}
onClick={() => {
setPlay(true);
console.log(play);}}>
<source src={src} type={type} key={index}/>
Your browser does not support the video tag.
</video>
</>
)
}
Related
How can I wait until all images are loaded in React.JS?
The problem is that I do some calculations (image processing) using those images and the results are different between multiple refreshes of the browser because at certain times the calculations start before the images are 100% loaded. Is there a way to wait until 100% of all images are loaded?
I've tried something like this:
const [imagesLoaded, setImagesLoaded] = useState(false);
{images.map((image, index) => {
return <ShowImage source={image} index={index+1} key={index} onLoad={() => setImagesLoaded(index)} />
})}
const ShowImage: React.FC<{source:string, index: number, onLoad: () => void}> = ({source, index, onLoad}) => {
return (
<img src={source} width="640" height="480" id={'image' + index} alt={'image' + index} onLoad={onLoad}/>
)
}
And the 'checker':
useEffect(() => {
if(imagesLoaded === 5) {
... do something
}
}, [imagesLoaded]);
But the problem is that this is working only for the first page render, if I refresh is not working, but I refresh one more time is working again and sometimes needs more refreshes, what's the problem?
You could refactor your ShowImage component to only set imagesLoaded when the last image source URL is loaded.
function ShowImages({ urls, setImagesLoaded }) {
const onLoad = (index) => {
if (index === urls.length - 1) {
setImagesLoaded(true)
}
};
return (
<>
{urls.map((url, index) => (
<img src={url} onLoad={() => onLoad(index)} key={url} />
))}
</>
);
}
export default ShowImages;
And use the component something like this
const [imagesLoaded, setImagesLoaded] = useState(false);
...
useEffect(() => {
if(imagesLoaded) {
... do something
}
}, [imagesLoaded]);
...
<ShowImages urls={images} setImagesLoaded={setImagesLoaded}/>
Working example here
Your images might not load in the intended order. If your 4th image loads after the 5th one, then the value of imagesLoaded will be 4 at the end.
To prevent that, I would increment the value one at a time, so when all five images are loaded the value will be 5.
onLoad={() => setImagesLoaded(v => v + 1)}
I'm using react-player https://github.com/cookpete/react-player to play my videos. My problem is, how can I pause other videos while selected video is playing?
const videoRef = useRef();
const updateVideoHandler = async (videoId, videoTitle) => {
setSelectedVideoId(videoId);
if (!selectedVideoId) {
videoRef?.current?.player?.player?.onPause();
}
};
<ReactPlayer
ref={videoRef}
onPlay={() => updateVideoHandler(video.id, video.title)}
playsinline={true}
playing={true}
controls={true}
url={video?.url}
width="100%"
height="100%"
playIcon={
<div
className="play-icon"
role="button"
tabIndex={0}
style={{ outline: "none" }}
>
{" "}
<img src="/images/play.png" alt="" />
</div>
}
light={video?.pic}
/>;
You could store all player instances in a Context and use a Provider and Consumer to pause all players if one starts playing.
Since you pass a playing boolean to ReactPlayer, you can easily store a id or reference of the current playing player.
For example:
PlayerProvider.jsx
export const PlayerContext = React.createContext({
play: (playerId) => true,
pause: (playerId) => true,
isPlaying: (playerId) => false,
});
function PlayerProvider({ children }) {
// store the id of the current playing player
const [playing, setPlaying] = useState('');
// set playing to the given id
const play = playerId => setPlaying(playerId);
// unset the playing player
const pause = () => setPlaying(false);
// returns true if the given playerId is playing
const isPlaying = playerId => playerId === playing;
return (
<PlayerContext.Provider value={{ play, pause, isPlaying }}>
{children}
</PlayerContext.Provider>
)
}
export default PlayerProvider;
Player.jsx
import { PlayerContext } from './PlayerProvider';
function Player({ video, id }) {
const { isPlaying, play, pause } = useContext(PlayerContext);
<ReactPlayer
ref={videoRef}
playsinline={true}
playing={isPlaying(id)}
controls={true}
url={video?.url}
width="100%"
height="100%"
onPause={() => pause(id)}
onEnded={() => pause(id)}
onClickPreview={() => play(id)}
playIcon={
<div
className="play-icon"
role="button"
tabIndex={0}
style={{ outline: "none" }}
>
{" "}
<img src="/images/play.png" alt="" />
</div>
}
light={video?.pic}
/>;
}
export default Player;
Page.jsx
import PlayerProvider from './PlayerProvider';
import Player from './Player';
function Page() {
return (
<PlayerProvider>
<Player video="/path/to/video1.mp4" id="player1" />
<Player video="/path/to/video2.mp4" id="player2" />
<Player video="/path/to/video3.mp4" id="player3" />
</PlayerProvider>
)
}
Actially this is very easy process to get
try it out
export const VideoPlayer = () =>{
const videoooo = useRef();
const pauseVideo = () => {
//at the place of pauseVideo you can use "stopVideo", "playVideo"
videoooo.current.contentWindow.postMessage(
'{"event":"command","func":"pauseVideo","args":""}',
"*"
);
};
return(<> <iframe
ref={videoooo}
id="myVideoId"
src="https://www.youtube.com/embed/Q63qjIXMqwU?enablejsapi=1"
></iframe>
<button
onClick={() => {
pauseVideo();
}}
>
Pause
</button></>)
}
it is very easy and useful syntax from js
// unset the playing player
const pause = () => setPlaying(false);
if you remove this line from the code it is working perfectly, when one video is already playing and you click on the second video, onPause is invoked and it is calling the pause function due to that setPlaying updating the playing value due to that page rerendering and in that time playing value is false and it does not match with any video id and that's why every video is stopped playing.
I implemented it using video-react here :
react-video-js
You need to use
controls,
preload='auto',
autoplay
Or
You can also pop-up a modal and show videos and use this
<div>
<button onClick={this.playVideo}>
Play!
</button>
<button onClick={this.pauseVideo}>
Pause!
</button>
</div>
where you need to store the states inside these onClick for play and pause depending upon the useref of a particular video else if you use a Modal then destroy it after close so that video doesn't play once you close.
I am building a simple music player but where I fail is at trying to execute one item from the array at a time. I am using React H5 Audio Player package to play the music. I am currently mapping through all the songs but I don't know how to properly play one at a time. I appreciate any help. I've been stuck on this for a few days.
import { SongContext } from '../../SongContext';
import AudioPlayer from 'react-h5-audio-player';
import 'react-h5-audio-player/lib/styles.css';
import './Player.css';
const Player = () => {
const { songs } = useContext(SongContext);
return (
<>
{songs.length > 0 &&
songs.map((song) => (
<div className="player" key={song.id}>
<AudioPlayer
// autoPlay
// src={song.preview}
showJumpControls={false}
customVolumeControls={[]}
customAdditionalControls={[]}
onPlay={() => console.log('playing')}
/>
</div>
))}
</>
);
};
export default Player;
Don't map all the songs at once, take a song by index (currentSong), and when it's done, use the onEnded event to increment the index, so the next one would play.
Example (codepen):
const Player = () => {
const { songs } = useContext(SongContext);
const [currentSong, setCurrentSong] = useState(0);
const song = songs[currentSong];
if(!song) return null; // don't render the player when no song is available
return (
<div className="player">
<AudioPlayer
autoPlay
src={song.preview}
showJumpControls={false}
customVolumeControls={[]}
customAdditionalControls={[]}
onPlay={() => console.log('playing')}
onEnded={() => setCurrentSong(i => i + 1)}
/>
</div>
);
};
So I'm building a simple react app that fetches a bunch of images and displays them as cards.
The intention is to show an info message until all the images have loaded, then removing the notice again.
const App = () => {
const [cardInfo, setCardInfo] = useContext(CardInfoContext)
useEffect(() => {
fetchData(setCardInfo)
}, [])
useEffect(() => {
const app = document.querySelector('.app')
for(const child of app.children){
app.removeChild(child)
}
const loadingNotice = document.createElement('h1')
loadingNotice.innerHTML = "Fetching data ..."
app.appendChild(loadingNotice) //<-- this never shows up
cardInfo.forEach( info => {
const img = document.createElement('img')
img.src = info.image
app.appendChild(img)
})
app.removeChild(loadingNotice)
}, [cardInfo])
return (
<>
<div className="app">
<h1>Fetching data...</h1>
</div>
</>
)};
What instead happens is the app stays blank until all the images are loaded, then shows all the images at once -- but never the loading notice.
Can I somehow "push" the loading indicator change to the UI independent of the rest of the rendering?
Another thing I tried was
const App = () => {
const [cardInfo, setCardInfo] = useContext(CardInfoContext)
useEffect(() => {
fetchData(setCardInfo)
}, [])
useEffect(() => {
const app = document.querySelector('.app')
if(!cardInfo) return
const loadingNotice = app.querySelector(".loadingNotice")
loadingNotice.style.display = 'block' //<-- this never shows up
cardInfo.forEach( info => {
const img = document.createElement('img')
img.src = info.image
app.appendChild(img)
})
loadingNotice.style.display = 'none'
}, [cardInfo])
return (
<>
<div className="app">
<h1 className="loadingNotice">Fetching data...</h1>
</div>
</>
)}
Which would be incorrect because I do need to remove all the images, at least, but even that only displayed the loading notice for a fraction of a second, then the component goes blank until all the images can be displayed.
useEffect observes when cardInfo is changed, not when the render the comes after fired. You can use useLayoutEffect instead.
...but it fires synchronously after all DOM mutations. Use this to read layout from the DOM and synchronously re-render. Updates scheduled inside useLayoutEffect will be flushed synchronously, before the browser has a chance to paint.
BTW, I wouldn't combine direct DOM manipulation with React to avoid issues like this (among other reasons)
Something like
const App = () => {
const [isLoadgin, setIsLoading] = useState(true)
const [cardInfo, setCardInfo] = useContext(CardInfoContext)
useEffect(() => {
fetchData(result => {
setCardInfo(result);
setIsLoading(false);
})
}, [])
return (
<>
<div className="app">
{isLoading && <h1 className="loadingNotice">Fetching data...</h1>}
{
cardInfo.map(card => <img src={card.image} />)
}
</div>
</>
)}
You need conditional rendering instead of all that DOM manipulation you are trying in the useEffect.
...
return(
<>
<div className="app">
{ !cardInfo ? <h1 className="loadingNotice">Fetching data...</h1> : <Cards info={cardInfo} /> }
</div>
</>
)
Note: I am assuming you have something like <Cards> component that displays cards details.
I'd like certain elements on my site to emit a sound when clicked. I easily did that by adding an audio element with a ref, and a function that plays the refs sound onClick.
const sound = require('../sounds/bird.mp3');
const soundRef = useRef(null);
const playSound = () => {
soundRef.current.play();
}
return <div>
<audio ref={soundRef}><source src={sound} /></audio>
<img src="bird.png" onClick={playSound} />
</div>
Since I now found out I may need to reuse this, I decided to create an Audio component to encapsulate the clicked element. I'd like it to receive the sound's file name as a property:
<Audio soundName="bird">
<div><img src="bird.png" /></div>
</Audio>
My problem is: in the Audio component, I get the soundName and children props and render the {children, but how do I add an onClick even to the child element, so it would trigger the Audio element playSound function?
What I currently have in the Audio component:
export default ({soundName, ...children}) => {
const sound = require(`../sounds/${soundName}.mp3`);
const soundRef = useRef(null);
const playSound = () => {
soundRef.current.play();
}
return <>
<audio ref={soundRef}><source src={sound} /></audio>
{children} // <--- this is where I need to somehow add the event
</>
}
I'm hoping I'm missing a tiny thing here...
You can wrap your children with something, like a div, who can listen for your event, something like:
export default ({soundName, ...children}) => {
const sound = require(`../sounds/${soundName}.mp3`);
const soundRef = useRef(null);
const playSound = () => {
soundRef.current.play();
}
return <>
<audio ref={soundRef}><source src={sound} /></audio>
<div onClick={ playSound }>
{children} // <--- this is where I need to somehow add the event
</div>
</>
}
I think this covers most of your cases.
There might be a children which intercept the event before the Audio component and prevent the event propagation to the parent, something like:
<Audio soundName="bird">
<img
src="bird.png"
onClick={ event => {
doSomethingOnThisImageClick()
event.stopPropagation()
}}
/>
</Audio>
If you know that this case might happen but you still want to play the file no matter what, you need to recognize the event in its capture phase, BEFORE the child component even know it, using the Capture variant of the event name, like:
export default ({soundName, ...children}) => {
const sound = require(`../sounds/${soundName}.mp3`);
const soundRef = useRef(null);
const playSound = () => {
soundRef.current.play();
}
return <>
<audio ref={soundRef}><source src={sound} /></audio>
{ /* notice here? */ }
{ /* | */ }
{ /* v */ }
<div onClickCapture={ playSound }>
{children}
</div>
</>
}