1

I have a component and need to wait for the component to mount properly. Until then, I would like to show a loading animation. How could I do this in React?

I would like to do this without state, as I have many stateless components that will need that kind of functionality. Is there any efficient way to do this? If not, how would I do this with state? Have a variable isLoading and then in componentDidMount set the variable to false and have a conditional rendering in my render()?

George Welder
  • 3,787
  • 11
  • 39
  • 75
  • What does mount properly mean in the case of this component? – Ori Drori Nov 02 '17 at 11:15
  • So, it's a component that shows some images. The images are animated, however, it takes some time to load the animation library. The problem is that until that animation library is loaded, the images are already seen on the screen - which I don't want to do. So I would like to put a loading / spinning animation on top. – George Welder Nov 02 '17 at 11:27

2 Answers2

2

In this case, is right to use state because only the component knows when the async call is finished.

I suggest to use 'react-loading' package.

import ReactLoading from 'react-loading'

class App extends React.Component {
  state = {
    isLoading: true
  };

  componentDidMount() {
    setTimeout(() => this.setState({ isLoading: false }), 2000); // do your async call
  }

  render() {
    if(this.state.isLoading) { // if doing asyng things
      return <ReactLoading type={type} color={color} height='667' width='375' />; // render the loading component
    }

    return (
      <div>Content</div>
    ); 
  }
}

ReactDOM.render(
  <App />,
  document.getElementById('app')
);
David Ginanni
  • 1,617
  • 15
  • 9
0

Pass a prop to component, something like loadingFinished={animationLibLoaded ? true : false}, and then render it conditionally in component's render() function, like loadingFinished ? (<AnimatedImages />) : <LoadingSpinner />)

Andrija Ćeranić
  • 1,633
  • 11
  • 14