DEV Community

Cover image for Simple HOC in React
Nabil Alamin
Nabil Alamin

Posted on • Originally published at arndom.hashnode.dev

2 1

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.

👋

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more