Skip to content

Instantly share code, notes, and snippets.

@JuoCode
Last active April 16, 2016 18:15
Show Gist options
  • Save JuoCode/2b6f51901e1877b590e853f8760e0df6 to your computer and use it in GitHub Desktop.
Save JuoCode/2b6f51901e1877b590e853f8760e0df6 to your computer and use it in GitHub Desktop.
Change button status when request.
var Button = React.createClass({
getInitialState: function () {
return { status: 'initial' };
},
componentWillReceiveProps: function (nextProps) {
var setState = this.setState.bind(this);
setState({ status: nextProps.status });
if (['success', 'error'].includes(nextProps.status)) {
setTimeout(function () {
setState({ status: 'initial', disabled: false });
}, 1500);
}
},
handleClick: function () {
this.setState({ status: 'loading', disabled: true });
this.props.onClick();
},
render: function () {
var status, buttonBody;
status = this.state.status
switch(status) {
case 'loading':
buttonBody = 'loading';
break;
case 'success':
buttonBody = 'Success';
break;
case 'error':
buttonBody = 'Error';
break;
default:
buttonBody = this.props.children;
break;
}
return (
<button onClick={this.handleClick} disabled={this.state.disabled}>{buttonBody}</button>
);
}
});
var App = React.createClass({
getInitialState: function () {
return { submitProgress: 'initial' };
},
handleCreate: function () {
alert('Request server...');
var setState = this.setState.bind(this);
setTimeout(function () {
setState({ submitProgress: (Math.random() * 2) > 1 ? 'success' : 'error' });
}, 2000);
},
render: function () {
return (
<Button
onClick={this.handleCreate}
status={this.state.submitProgress}>
Submit
</Button>
);
}
});
ReactDOM.render(
<App />,
document.getElementById('container')
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment