React simple Higher Order Component

106 Views Asked by At

My purpose is to make a simple Higher Order Component where I have a reusable Section component and where I maybe define some css classes and the <section> tag:

import React from 'react'

function SectionWrapper(props) {
  return <section>{props.children}</section>
}

export default SectionWrapper

Now in my Parent component I can wrap my child-section components like this:

<SectionWrapper>
  <SectionTitle />
</SectionWrapper>

<SectionWrapper>
  <List />
</SectionWrapper>

Is there a cleaner way to achieve this? E.g. how do I pass the child-component as a prop?

2

There are 2 best solutions below

0
On

Yes, you could do -

const withSection = (Component) => (props) =>
 <section><Component {...props}/></section>

const EnhancedSectionTitle = withSection(SectionTitle)

Then use it like

<EnhancedSectionTitle />

Rename EnhancedSectionTitle to whatever makes sense in your app

0
On

You could convert the section wrapper to a Higher Order Component as such:

const withSection = Component => props => (
  <section>
    <Component {...props} />
  </section>
);

Ensure you return a valid react component that allows props to be passed through to the underlying component being wrapped.

Usage:

const ComponentWithSection = withSection(MyComponent);

...

<ComponentWithSection myProp={myAwesomeProp} />