Bomber Bomber - 2 months ago 39
React JSX Question

Hide/Show component using componentDidMount

I'm trying to get a loading spinner component to display using

componentDidUpdate
which sets the
state
to
true
. The loader doesn't show, just a white space until the
buildPosts()
renders. How can I display the
Loader
component while the function executes?

constructor() {
super();
this.state = {loaded: false};
}


onLoaded(){
this.setState({loaded: true });
}

componentDidUpdate() {
this.onLoaded();
}

buildPosts(posts) {
return posts.map(post =>
<Post post={post} key={post.id} />
);
}
render() {
const { posts, totalPages, pageNum = 1 } = this.props;


return (
this.state.loaded ?
(<div id="blog">
{this.buildPosts(posts)}
{this.buildPagination(parseInt(pageNum), totalPages)}
</div>) : <Loader />
);
}

Answer

Assuming that your loader will be showed when there is no post. You may not need the load state. How about this way :

  render() {
    const { posts, totalPages, pageNum = 1 } = this.props;


        return (
            posts !== undefined && posts.length > 0 ? 
            (<div id="blog">
                {this.buildPosts(posts)}
                {this.buildPagination(parseInt(pageNum), totalPages)}
            </div>) : <Loader /> 
        );
  }