I have a component that displays images. The component has a menu bar as well.
During initially server request, this component always shows the menu bar for a split second because the actually image is not loaded yet.
How to display the menu bar only after the image is ready?
EDITED:
I can determine when the URLs to the images are loaded and available. But how to tell if the actually image itself is ready?
CodePudding user response:
Actually I have a workaround, which might be valid in your case : you can add loading for some seconds until images is rendered successfully, I hope this help you
CodePudding user response:
You can have a loading state set to true by default like so :
const [loading, setLoading] = useState(true);
After you have all your data fetched, you set it to false like so :
setLoading(false)
And you render will be something like this :
return (<div>
{loading ? <p>loading...</p> : <MyComponent/>}
</div>)
CodePudding user response:
You can use partial rendering for example
import React, { useEffect, useState } from 'react';
function App() {
const [data, setData] = useState(null);
useEffect(()=>{
setData(true);
}, []);
return (
<div>
{data && <div> after data is not null this will be visible</div>}
</div>
);
}
export default App;
CodePudding user response:
You can set a state as below and load the menu based on this value;
const [ImageLoaded, setImageLoaded] = useState(false);
CodePudding user response:
You can do it like this:
function YourComponent () {
const [imgLoaded, setImgLoaded] = useState(false);
const handleImgLoad = () => {
setImgLoaded(true);
}
return(
<>
<img onLoad={handleImgLoad} src="..." alt="..." />
{imgLoaded ? <MenuBar /> : <></>}
</>
);
}