Skip to content

Instantly share code, notes, and snippets.

@dmitru
Last active September 14, 2017 15:15
Show Gist options
  • Save dmitru/57953978171de614dcf0eb100d26f450 to your computer and use it in GitHub Desktop.
Save dmitru/57953978171de614dcf0eb100d26f450 to your computer and use it in GitHub Desktop.
A React wrapper component for Ladda library - buttons with spinners
import React from 'react';
import PropTypes from 'prop-types';
import ReactDOM from 'react-dom';
import Ladda from 'ladda';
import cx from 'classnames';
export default class SpinnerButton extends React.Component {
static propTypes = {
loading: PropTypes.bool,
className: PropTypes.string,
};
static defaultProps = {
loading: false,
className: null,
};
constructor(props) {
super(props);
this._ref = null;
this._ladda = null;
}
_saveRef = (ref) => {
this._ref = ref;
if (this._ref) {
this._ladda = Ladda.create(ReactDOM.findDOMNode(this._ref));
window.lad = this._ladda;
this.updateLoadingState(this.props.loading);
} else {
this._ladda = null;
}
}
updateLoadingState = (loading) => {
if (!this._ladda) {
return;
}
if (loading) {
this._ladda.start();
} else {
this._ladda.stop();
}
};
componentWillReceiveProps(nextProps) {
if (nextProps.loading !== this.props.loading) {
this.updateLoadingState(nextProps.loading);
}
}
componentWillUnmount() {
this._ladda.remove();
}
render() {
const { className, loading, children, ...otherProps } = this.props;
return (
<button
ref={this._saveRef}
className={cx('ladda-button', className)}
{...otherProps}
>
{children}
</button>
);
}
}
@dmitru
Copy link
Author

dmitru commented Sep 14, 2017

Usage example:

        <SpinnerButton
          data-style="slide-left"
          className="btn  btn-default"
          loading={!this.state.spinnerButtonEnabled}
          onClick={() => this.setState({ spinnerButtonEnabled: !this.state.spinnerButtonEnabled })}
        >
          Click me
        </SpinnerButton>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment