Ad

Default Values For Higher Order Components In React

Say I have a higher order component:

interface MyHOCInterface { title: string }

export function wrapMyHoc<T extends MyHOCInterface>(
  Component: React.ComponentType<T>,) {
  return class extends React.Component<T> {
    state = {...this.props,}
    const {title} = {...(this.props as T)}
    render() {
      return(
        <>
          {title}
          <Component {...this.props as T} />
        </>
      )
    }
  }
}

And then some components that I define like this:

export const MyFirstComponent = wrapMyHoc(
  (props: MyHocInterface) => (<></>)
)

export const MySecondComponent = wrapMyHoc(
  (props: MyHocInterface) => (<></>)
)

Naturally, this would allow me to render them like below. I noticed this code (all instances of the MySecondComponent component always has the same title):

<>
  <MyFirstComponent title='my first title'/>
  <MySecondComponent title='my second title' />
  <MySecondComponent title='my second title' />
  <MySecondComponent title='my second title' />
</>

How would I go about putting a default value so I can write the following and still have my second title as the title:

<> <MySecondComponent /> </>
Ad

Answer

Based on your last comment about MySecondComponent usig another HOC, I think you can do it something like this:

const doubeWrappedHOC = Component => {
  const HOC = wrapMyHoc(Component);
  return props =>
    props.title === undefined &&
    Component === MySecondComponent
      ? HOC({ ...props, title: defaultValue })
      : HOC(props);
};

It is not in TypeScript and MySecondComponent has to be in scope/inported but all your components could use this HOC instead of using another HOC just for MyCompnent. If you want to create MyCompnent with a diffeerent HOC then you can leave out && Component === MySecondComponent. Re use logic wrapMyHoc again and just set a default for title.

Ad
source: stackoverflow.com
Ad