Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 705
YannPl Avatar asked Feb 12 '23 11:02

YannPl


1 Answers

For a mixin this is about the best you can do. It's just a simple early return in render.

var AuthentLevelMixin {
  isAuthenticated: function(){
    return Auth.check();
  }
};

var C = React.createClass({
    mixins: [AuthentLevelMixin],
    render: function(){
      if (!this.isAuthenticated()) return <div />;
      return (
         <div>...</div>
      );
    }
});

If you decide to go with your initial strategy (I don't recommend it), it just needs to be modified slightly:

// more explicit names are important for dirty code
var PreventRenderUnlessAuthMixin = {
    componentWillMount: function() {
        this._originalRender = this.render;
        this._setRenderMethod();
    },
    componentWillUpdate: function(){
        this._setRenderMethod();
    }.

    _emptyRender: function () {
        return <span />;
    },
    _setRenderMethod: function(){
        this.render = Auth.check() ? this._originalRender : this._emptyRender;
    }
}
like image 143
Brigand Avatar answered Feb 13 '23 23:02

Brigand