Authorize your React Components with Higher-Order Component

Before we begin this, please assume the following:
We will discuss about and not (-Our React App is storing Logged-In user’s Role in localStorage(you can put it anywhere in the browser).

Let’s build the basement first… 🏃 🏃🏃🏃🏃

  1. HOC (Higher-Order Component):
    The word sounds so cool 🆒 but it is little bit confusing as it’s not exactly a component but a

You heard it right, Higher-Order Component is a function and not a component. Let me show you it’s definition:

HOCs are functions to which we pass our components and they can bring some transformation to it and return back a new component. If you have ever used Redux or Material-UI, you would have seen something like connect and withStyles. Connect and withStyles are HOCs which transforms our component and returns back a new component. If we talk specifically about connect, it injects props in our component which we name as and .
Did you just say something like map??? map can also be assumed as a HOC which takes an array and return a transformed array.

2. I assume you have basic knowledge of React, so let’s jump directly into Authorizing our React Components. Many a times, we have requirement to hide something from a normal user but show it to Admins.

Let’s say, we have a <ServerMonitor /> component which we don’t want to show to normal users and only to Admins. So we will create a HOC for authorizing our components to which we can pass any component we want to authorize.

The withAuthorization HOC is not so fancy, it is just checking if the current_user is Admin, then allow the component to render else send null to prevent the component from rendering.

Here in the above snippet, we are passing our ServerMonitor component to the withAuthorization HOC and exporting the returned value. If the current_user is an then the same component is returned and hence is exported else null is returned and exported which leads to preventing the ServerMonitor component from rendering in the DOM.

Caveat 😢 😢

Here we are authorizing the components based on UserRole stored in the localStorage which can be changed easily and can be replaced with Admin or anything. So we should have Authorization in our Back-end too in order to prevent data getting exposed to anyone trying to tamper the localStorage.

Thanks for reading it till the end. Hope it helped you and you enjoyed it. 😍 😍

If you need any help related to React, Ruby on Rails or Javascript, you can freely connect with me at

I am a fullStack developer building things at BigBinary using Ruby on Rails and React.js .

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store