Neon Power Mains

    set-state-function-mixin

    0.1.4 • Public • Published

    set-state-function-mixin

    Build Status npm version

    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 })

    Install

    npm i set-state-function-mixin

    DownloadsWeekly Downloads

    4

    Version

    0.1.4

    License

    MIT

    Last publish

    Collaborators

    • moodysalem