Reputation: 1
I have a List component which takes some time to be loaded.
I want it to show a spinner until it is loaded and mounted but unfortunately everything I try does not work.
I am trying to do something like this:
class List extends React.Component {
constructor(props) {
super(props);
this.state = {
isReady: false,
};
}
componentDidMount() {
this.setState({isReady: true});
}
render() {
if(this.state.isReady){
return (
<Content>
{this.renderList()}
</Content>
);
}
else {
return (
<Spinner/>
);
}
}
renderList() {
return this.props.data.map((item, index) => {
return (
<ListItem type={this.props.type} text={item} key={index}/>
);
});
}
}
What I am doing wrong?
Upvotes: 0
Views: 650
Reputation: 1267
I think you should init isLoading
state to be true
in constructor
, then set it to false
in componentDidMount
.
Then try to render <Spinner />
while isLoading
is true
Upvotes: 0
Reputation: 1032
You should be checking both the props.data and the state.isReady in a case where you don't know which would come first:
render() {
if(this.state.isReady && this.props.data.length !== 0){
return (
<Content>
{this.renderList()}
</Content>
);
}
else {
return (
<Spinner/>
);
}
}
Upvotes: 1