ReactJS Spinner

Writing a spinner component which displays ... animated using ReactJS is super easy using TypeScript + JSX (TSX).

First, define the SpinnerState interface.

interface SpinnerState
{
   frame:number;
}

Next define the Spinner component.
The Spinner component has state which conforms to the SpinnerState interface.

class Spinner extends React.Component<any, SpinnerState>
{
}

Next define the constructor inside the Spinner to initialize the state:

constructor(props)
{
   super(props);
   this.state = {frame:0};
}

Define the render method which will take care of the actual rendering.

render()
{
   return
<div>{Array(this.state.frame + 2).join(".")}</div>
}

Define the running flag, componentDidMount method and componentWillUnmount method.

private running = true;
componentDidMount()
{
   let interval = 100;
   let f = ()=>
   {
      if (this.running)
      {
         let frame = this.state.frame;
         frame++;
         if (frame &amp;gt; 5)
         {
            frame = 0;
         }
         this.setState({frame:frame});
         setTimeout(f, interval);
      }
   }
   setTimeout(f, 0);
}
componentWillUnmount()
{
   this.running = false;
}

Thats it! using the component is as simple as writing:

 <Spinner/> 

inside another react component.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s