title: Hide some React component children depending on user role
body: <p>I am writing a single page application in React and Redux (with a Node.js backend).</p>
  
  <p>I want to implement role-based access control and want to control the display of certain parts (or sub parts) of the app.</p>
  
  <p>I'm going to get permissions list from Node.js, which is just an object with such structure:</p>
  
  <pre><code>{
    users: 'read',
    models: 'write',
    ...
    dictionaries: 'none',
  }
  </code></pre>
  
  <p><strong>key</strong> is protected resource,</p>
  
  <p><strong>value</strong> is user permission for this resource (one of: <code>none</code>, <code>read</code>, <code>write</code>).</p>
  
  <p>I'm storing it into redux state. Seems easy enough.</p>
  
  <p><code>none</code> permission will be checked by <code>react-router</code> routes <code>onEnter/onChange</code> hooks or <code>redux-auth-wrapper</code>. It seems easy too.</p>
  
  <p>But what is the best way to apply <code>read/write</code> permissions to any component view (e.g. hide edit button in Models component if the user has <code>{ models: 'read' }</code> permission).</p>
  
  <p>I've found <a href="https://discuss.reactjs.org/t/user-permissions/3752/3" rel="noreferrer">this solution</a> and change it a bit for my task:</p>
  
  <pre><code>class Check extends React.Component {
    static propTypes = {
      resource: React.PropTypes.string.isRequired,
      permission: React.PropTypes.oneOf(['read', 'write']),
      userPermissions: React.PropTypes.object,
    };
  
    // Checks that user permission for resource is the same or greater than required
    allowed() {
      const permissions = ['read', 'write'];
      const { permission, userPermissions } = this.props;
      const userPermission = userPermissions[resource] || 'none';
  
      return permissions.indexOf(userPermission) &gt;= permissions.indexOf(permission)
    }
  
    render() {
      if (this.allowed()) return { this.props.children };
    }
  }
  
  export default connect(userPermissionsSelector)(Check)
  </code></pre>
  
  <p>where <code>userPermissionsSelector</code> would be something like this: <code>(store) =&gt; store.userPermisisons</code> and returns user permission object.</p>
  
  <p>Then wrap protected element with <code>Check</code>:</p>
  
  <pre><code>&lt;Check resource="models" permission="write"&gt;
    &lt;Button&gt;Edit model&lt;/Button&gt;
  &lt;/Check&gt;
  </code></pre>
  
  <p>so if user doesn't have <code>write</code> permission for <code>models</code> the button will not be displayed.</p>
  
  <p>Has anyone done anything like this? Is there more "elegant" solution than this?</p>
  
  <p>thanks! </p>
  
  <p><strong>P.S.</strong> Of course user permission will also be checked on the server side too.</p>