Skip to content

Instantly share code, notes, and snippets.

@akhil-gautam
Created April 24, 2019 16:26
Show Gist options
  • Save akhil-gautam/fbf08776da3683ce9abe85cc86105fbf to your computer and use it in GitHub Desktop.
Save akhil-gautam/fbf08776da3683ce9abe85cc86105fbf to your computer and use it in GitHub Desktop.
A Higher-Order Component to Authorize your React Components
import * as React from 'react';
// other parameters like allowed roles can also be passed to this HOC
// depending on your requirement.
export const withAuthorization = (OriginalComponent:any) => {
return class extends React.Component {
render(){
// as I mentioned earlier, we are storing current_user's role
// in localStorage(can be tampered easily)
const currentUserRole:string = window.localStorage.getItem('user_role');
// we will return null if the user is not Admin else we will return
// back the component as it is(ofcourse you can modify it like add some extra props to it)
return(
currentUserRole !== 'admin' ?
null : <OriginalComponent {...this.props} />
);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment