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
and change line from
to