ReactJS Spinner
January 05, 2017 - Søren Alsbjerg HørupWriting 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 == 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.