DEV Community

Cover image for Simple HOC in React
Nabil Alamin
Nabil Alamin

Posted on • Originally published at arndom.hashnode.dev

Simple HOC in React

Higher Order Components allow for reusability of code and saves you from repeating yourself, it comes in quite handy. It is something that recently came to my attention and I only wish I had learnt this earlier.

In this instance, I had a layout that consisted of a top nav embedded with a drawer that appeared in multiple views but not all, so instead of always importing it I made it a HOC like this:

import React from 'react'
import TopNav from '../components/TopNav'

export const WithLayout = (Component)  => {
    return (props) => (
        <div>
            <TopNav/>
            <Component {...props}/>
        </div>
    )
}

Enter fullscreen mode Exit fullscreen mode

So what this allows you to do is wrap any component you want to have a top nav in this Layout component, just like this:

import React from 'react'
import { WithLayout } from '../HOC/Layout'

const Landing = () => {
    return (
        <div>
            <p>This a page that uses the layout HOC </p>
        </div>
    )
}

export default WithLayout(Landing)

Enter fullscreen mode Exit fullscreen mode

And with that, you have a functional HOC in your react app.

👋

Discussion (0)