score:0

Accepted answer

i think higher order components (hoc) are also a good candidate for this. you can basically wrap any component in hoc that defines some behaviour and decides if it should render a wrappe.

nicest way to do this would be if you're using a es2015 transpiler with some es2016 features enabled (namely decorators):

function withroles(roles) {
  return function(component) {
    return class componentwithroles extends react.component {
      constructor(props) {
        super(props)
        // not sure where the data to get your roles about current user?
        // from but you could potentially to that here if i'm getting your point
        // and also setup listeners
        this.state = { currentuser: 'admin' }
      }

      validateroles() {
        // you have access to the ``roles`` variable in this scope
        // you can use it to validate them.
        return true;
      }

      render() {
        if (this.validateroles()) {
          return <component {...this.props} />;
          )
        } else {
          return <div>nope...</div>;
        }
      }
    }
  }
}

// you can then use this on any component as a decorator
@withroles({ showonlyfor: [ 'admin' ] })
class adminonlycomponent extends react.component {
  render() {
    return <div> this is secert stuff </div>
  }
}

i've used es2016 features because i think it's nicer to get the point across but you can implement that with just a simple function wrapping, here's a gist by one of the react core members on the topic of hoc: https://gist.github.com/sebmarkbage/ef0bf1f338a7182b6775

score:1

i came up with this solution:

var rolesrequired = react.createclass({
    permitted: roles => ...,

    render: function () {
        if (!this.permitted(this.props.roles)) {
            return null;
        }

        return <div>{this.props.children}</div>;
    }
});

what i'm doing is wrapping the children being returned in a <div> but i'm having to add an unwanted/unneeded dom element to achieve it.


Related Query

More Query from same tag