Search code examples
javascriptmixinsreactjs

React js - Disable render of a component in a mixin


I'm trying to develop a React mixin to check the user access level before rendering the component.

If the user doesn't have the permission to see the component, I would like to disable the rendering of the component. I've been looking for something build in react to handle this but found nothing, so I did that:

var AuthentLevelMixin = {
    componentWillMount: function() {
        if(!Auth.check()) {
            // Disable component render method
            this.render = function () {
                return false;
            }
        }
    }
}

It works as expected but I feel like it's the "dirty way".

So my question is: what is the "React way" for doing the same as this snippet ?


Solution

  • If you want to handle the authorization inside your mixin without adding logic to your component you are doing it the right way. BUT: Every component implementing this mixin should then be aware of what happens within this mixin. If the result you expect is, that nothing is rendered, then you are perfectly right with what you are doing. So if your way is resulting in simplicity it is the React-Way. And in my Opinion this is the case.

    In the componentWillMount lifecycle event you will capture the moment right before rendering - which is a great time to prevent rendering. So I really dont see anything speaking against your code.

    EDIT:

    aproach of defining: "react way"

    Once you have the same input resulting in the same output every time your code becomes predictable. With your code being predictable you achieve simplicity. These are terms used by Pete Hunt to describe the intentions of React. So therefor if you stay predictable and in result achieving simplicity you are doing it the react way.

    In case of the above mixin both these rules apply and is therefor the "react way" in the definition I have provided above.