how to write react hook HOC

Viewed 40

I got a page like this. I want use it to wrap other small components and put them in the router. My react router is version 5.0

import styled from 'styled-components'
import Footer from '../footer/Footer'
import Header from '../header/Header'

const PageWrap: any = ({ children }) => {
    return (
        <>
            <Header />
            <div className="other-small-comp">{children}</div>
            <Footer />
        </>
    )
}
export default PageWrap

With a function PageWrap, I want to be able to do something like this in the route

import Account from './Account'
Import Login from './Login'
<Switch>
    <PrivateRoute path={urls.account} exact component={PageWrap(Account)} />
    <Route path={urls.login} exact component={Login} />
</Switch>

How can I do PageWrap(Account) without error ?

1 Answers

The mistake you are making is that your wrapper is a React component that takes props as an argument instead of being a function that takes another component as an argument. In order to show you how to create a wrapper, I will use the AirBnb style guide example:

export default function withFoo(WrappedComponent) {
  function WithFoo(props) {
    return <WrappedComponent {...props} foo />;
  }

  const wrappedComponentName = WrappedComponent.displayName
    || WrappedComponent.name
    || 'Component';

  WithFoo.displayName = `withFoo(${wrappedComponentName})`;
  return WithFoo;
}
Related