I am trying to show a loading screen until a component within a main parent component loads its background image. Most of the articles I found were dealing with images placed directly into the DOM as tags. I have a component that uses a background image.
Here is my Home component which acts as my main container for all components:
class Home extends React.Component {
constructor() {
super();
}
render() {
return (
<div>
<Helmet>
<link id="favicon" rel="icon" href="../SB.png" type="image/x-icon"/>
<title>Snow Bounds</title>
</Helmet>
<CustomNavBar />
<HeroUnit />
<RoadMap />
<TeamFAQ />
<Footer />
</div>
)
}
}
export default Home;
The component in question is the HeroUnit Component which is as follows:
class HeroUnit extends React.Component {
render()
{
return (
<div id="home" className={`fullHeightContainer m-auto bg-primary-hero grad bg-info py-4`} style={{position: "relative"}}>
<Snowfall snowflakeCount={50} color={"rgba(255, 255, 255, .2)"} />
<Container className="h-100">
<div className="heroMainBG h-100" style={{position: "relative",zIndex: 1000}}>
</div>
</Container>
</div>
)
}
}
export default HeroUnit;
How can I make a loading screen show up until the Hero Unit heroMainBg is loaded?
Let me know if you need any other code.. :)
Just use this
class Home extends React.Component {
constructor() {
super();
this.state = {
loaded: false;
}
}
render() {
window.addEventListener("load", event => {
var image = document.querySelector('add the id or className');
var isLoaded = image.complete && image.naturalHeight !== 0;
if(isLoaded)this.setState({loaded:true});
alert(isLoaded); // this tells you whether the image has loaded or not
});
return (
this.state.loaded&&<div>
<Helmet>
<link id="favicon" rel="icon" href="../SB.png" type="image/x-icon"/>
<title>Snow Bounds</title>
</Helmet>
<CustomNavBar />
<HeroUnit />
<RoadMap />
<TeamFAQ />
<Footer />
</div>
)
}
}
export default Home;
You can add a loader when the image is not loaded : something like this :
!this.state.loaded?<Loader />:Your whole component