0.1.4 • Published 9 years ago
set-state-function-mixin v0.1.4
set-state-function-mixin
Shortcut for writing small functions to set state
Install
npm install set-state-function-mixin
Example
How many times have you written this code?
var MyModal = require('./SomeModal');
React.createClass({
getInitialState: function () {
return {
modalOpen: false
};
},
openModal: function () {
if (this.isMounted()) {
this.setState({
modalOpen: true
});
}
},
closeModal: function () {
if (this.isMounted()) {
this.setState({
modalOpen: false
});
}
},
render: function () {
return React.DOM.div({}, [
React.DOM.button({ onClick: this.openModal }),
MyModal({ onClose: this.closeModal })
]);
}
});
Instead, write this code using this mixin
var MyModal = require('./SomeModal');
React.createClass({
mixins: [ require('set-state-function-mixin') ]
getInitialState: function () {
return {
modalOpen: false
};
},
render: function () {
return React.DOM.div({}, [
React.DOM.button({ onClick: this.setStateFunction('modalOpen', true) }),
MyModal({ onClose: this.setStateFunction('modalOpen', false) })
]);
}
});
Or pass an object to the first argument to set multiple state variables
this.setStateFunction({ modalOpen: true, viewingModal: true })