Created
February 5, 2016 19:17
-
-
Save alfondotnet/c9f14229cdfd08882c07 to your computer and use it in GitHub Desktop.
Request Confirmation decorator for React Component methods.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Full Proof of Concept here http://jsbin.com/hupejawequ/1/edit?html,css,js,output | |
@requireConfirmation(["pay"]) // only request confirmation for the 'pay' method | |
class FormWithButton extends React.Component { | |
constructor() { | |
super(); | |
// We have to bind, () => {} doesnt work | |
this.pay = this.pay.bind(this); | |
this.request = this.request.bind(this); | |
} | |
pay() { | |
console.log("amount paid"); | |
} | |
request() { | |
console.log("amount requested"); | |
} | |
render() { | |
return (<div> | |
<h1>This is a form {this.props.name}</h1> | |
<button onClick={this.pay}>I want to pay</button> | |
<button onClick={this.request}>I want to request payments</button> | |
</div>); | |
} | |
} | |
React.render( | |
<FormWithButton name="importing things"/>, | |
document.getElementById("mount") | |
); | |
function requireConfirmation(methods) { | |
return function (ChildComponent) { | |
return class ConfirmationModal extends React.Component { | |
constructor() { | |
super(); | |
this.confirmationAccept = this.confirmationAccept.bind(this); | |
this.state = { | |
showModal: false, | |
methodToCallWhenOk: null, | |
}; | |
} | |
showConfirmation() { | |
return this.state.showModal ? (<div className="confirmation"> | |
<p>Confirmation required</p> | |
<p><button onClick={this.confirmationAccept}>Ok!</button></p> | |
</div>) : null; | |
} | |
toggleConfirmation(method) { | |
this.setState({ | |
showModal: true, | |
methodToCallWhenOk: method, | |
}); | |
} | |
confirmationAccept(e) { | |
e.preventDefault(); | |
this.setState({ showModal: false }); | |
this.state.methodToCallWhenOk.apply(this,arguments); | |
} | |
render() { | |
const Modal = ReactBootstrap.Modal; | |
const that = this; | |
const ccPrototype = ChildComponent.prototype; | |
for(let m of methods) { | |
const originalMethod = ccPrototype[m]; | |
ccPrototype[m] = function () { | |
that.toggleConfirmation(originalMethod); | |
return true; | |
} | |
} | |
return (<div> | |
<ChildComponent {...this.props} /> | |
{this.showConfirmation()} | |
</div>); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment