Toby Toby - 1 year ago 145
React JSX Question

Execute function in stateless component after timeout

I have a loading spinner in a stateless functional component that I'm using while I check for props.

I'd like to use

to have the loading spinner display for 5 seconds and then change the content if props are still not available, but this code doesn't seem to work:

function LoadingIndicator() {
let content = <span>Loading Spinner Here</span>;
setTimeout(() => {
console.log('6 second delay');
content = <span>Page could not be loaded.</span>;
}, 6000);
return (

I believe this doesn't work because nothing tells react to re-render this component, but I'd prefer not to upgrade to a container if possible.

Answer Source

Move the timer to the parent. Have the timer change a state value and in its render, pass that state value as a prop to your LoadingIndicator.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download