I'm trying to implement a pre-loader in React,
I tried the following
class MainApp extends React.Component {
ponentDidMount() {
this.preloader.style.display = 'none';
}
render() {
return (
<div id="loader-container" ref={(c) => { this.preloader = c; }} />
<SomeComponent />
);
}
}
However, it seems that the pre-loader disapper long before the load is plete.
How can I bind the removal of the pre-loader to the load event?
I'm trying to implement a pre-loader in React,
I tried the following
class MainApp extends React.Component {
ponentDidMount() {
this.preloader.style.display = 'none';
}
render() {
return (
<div id="loader-container" ref={(c) => { this.preloader = c; }} />
<SomeComponent />
);
}
}
However, it seems that the pre-loader disapper long before the load is plete.
How can I bind the removal of the pre-loader to the load event?
Share Improve this question asked Oct 20, 2017 at 5:02 Liron TovalLiron Toval 891 gold badge1 silver badge8 bronze badges2 Answers
Reset to default 1Ok so I used
window.addEventListener('load', this.handleLoad);
In ponentDidMount
and
handleLoad() {
$('#loader-container').hide(); // $ is available here
}
seems to do the job
Thanks
I think the problem is that you're hiding the loader container when your parent ponent (MainApp) is mounted and the request probably is not finished yet.
You could pass to the child ponent a function to call when the load is pleted like this:
class MainApp extends React.Component {
constructor (props) {
super(props);
this.hideLoader = this.hideLoader.bind(this);
}
hideLoader() {
this.preloader.style.display = 'none';
}
render() {
return (
<div id="loader-container" ref={(c) => { this.preloader = c; }} />
<SomeComponent onLoaded={this.hideLoader} />
);
}
}
And in SomeComponent
you should call this.props.onLoaded()
when the request is finished. Something like this:
class SomeComponent extends React.Component {
ponentWillMount () {
fetch(url)
.then(response => {
this.setState(...);
this.props.onLoaded();
});
}
}