How to implement Role based restrictions/permissions in react redux app?

前端 未结 5 2134
醉梦人生
醉梦人生 2021-02-06 12:18

I have a React-Redux-KoaJs application with multiple components. I have few user roles as well. Now i want to display few buttons, tables and div to only specific roles and hide

5条回答
  •  情话喂你
    2021-02-06 12:48

    You can check the role or permission in every component as @Eudald Arranz proposed. Or you can write a component that will checks permissions for you. For example:

    import PropTypes from 'prop-types';
    import { connect } from 'react-redux';
    
    const ShowForPermissionComponent = (props) => {
        const couldShow = props.userPermissions.includes(props.permission);
        return couldShow ? props.children : null;
    };
    
    ShowForPermissionComponent.propTypes = {
        permission: PropTypes.string.isRequired,
        userPermissions: PropTypes.array.isRequired
    };
    
    
    const mapStateToProps = state => ({
        userPermissions: state.user.permission //<--- here you will get permissions for your user from Redux store
    });
    
    export const ShowForPermission = connect(mapStateToProps)(ShowForPermissionComponent);
    

    and then you can use this component like this:

    import React from 'react';
    import { ShowForPermission } from './ShowForPermission';
    
    cons MyComponent = props => {
       return (
            
    ); }

提交回复
热议问题