简体   繁体   中英

Error with HOC in Role Based Authorization in React

I have been trying implement to Role Based Authorization in React as below

In authorization.js, it is checked if the logged-in user with his role, is allowed to access the page or not:

import React from "react";

const Authorization = (WrappedComponent, allowedRoles) => {
  return class WithAuthorization extends React.Component {
    constructor(props) {
      super(props);

      this.state = {
        user: {
          name: "vcarl",        
          role: "Admin"
        }
      };
    }
    render() {
      const { role } = this.state.user;
      if (allowedRoles.includes(role)) {
        return <WrappedComponent {...this.props} />;
      } else {
        return <h1>No page for you!</h1>;
      }
    }
  };
};

export default Authorization;

In App.js

render() {
    const accounts = Authorization(["SuperAdmin", "Admin"]);

    return (
      <StateContext.Provider value={{ ...this.state }}>
        <Router>                   
            <Route
              exact
              path="/accounts"
              component={accounts(Accounts)}
            />         
        </Router>
      </StateContext.Provider>
    );
  }

In Accounts.js:

import React, { Component } from "react";

class Accounts extends Component {
  render() {
    return <div>Accounts page</div>;
  }
}

export default Accounts;

But get the error:

TypeError: Class constructor WithAuthorization cannot be invoked without 'new'

Any suggestions?

You're trying to return class But in React philosophy component should return JSX or modified Children component So you need to remove

return class WithAuthorization extends React.Component {

and change line from

return <WrappedComponent {...this.props} />;

to

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM