Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass props through a higher order component from a Route

I have a problem with my Higher Order Component. I am trying to pass props from a <Layout /> component down a route (React Router v4). The components specified in the routes are wrapped by a HOC, but the props that I pass never reaches the component.

Also, I can't use the HOC without using export default () => MyHOC(MyComponent). I can't figure out why, but that might have something to do with it?

Layout.js

const Layout = ({ location, initialData, routeData, authenticateUser }) => (
  <Wrapper>
    <Container>
        <Switch>
          // how do I get these props passed through the HOC? render instead of component made no difference.
          <Route exact path="/pages/page-one" component={() => <PageOne routeData={routeData} title="PageOne" />} />
          <Route exact path="/pages/page-two" component={() => <PageTwo routeData={routeData} title="PageTwo" />} />
          <Route component={NotFound} />
        </Switch>
    </Container>
  </Wrapper>
)

export default Layout

Page.js

// I've tried swapping to (WrappedComponent) => (props) without success
const Page = (props) => (WrappedComponent) => {
 const renderHeader = props.header
   ? <Header title={props.headerTitle} />
   : false
 return (
   <Wrapper>
     {renderHeader}
     <Container withHeader={props.header}>
       <WrappedComponent />
     </Container>
   </Wrapper>
 )
}

export default Page

PageOne.js

class PageOne extends React.Component {
  render() {
    return (
      <Content>
        <Title>{this.props.title}</Title> // <----- not working!
        {JSON.stringify(this.props.routeData, null, 4)} // <---- not working!
      </Content>
    )
  }
}

export default () => Page({ header: true, headerTitle: 'header title' })(PageOne)

// does not work without () => Page
// when using just export default Page I get the "Invariant Violation: Element type is invalid: 
// expected a string (for built-in components) or a class/function (for composite components)
// but got: object. Check the render method of Route." error.
like image 355
Erik Hellman Avatar asked Jun 22 '17 08:06

Erik Hellman


1 Answers

You need one more arrow to make your Page to be a HOC. It takes params, wrapped component and has to return a component. Yours were rendering after getting WrappedComponent

const Page = (props) => (WrappedComponent) => (moreProps) => {
 const renderHeader = props.header
   ? <Header title={props.headerTitle} />
   : false
 return (
   <Wrapper>
     {renderHeader}
     <Container withHeader={props.header}>
       <WrappedComponent {...moreProps} />
     </Container>
   </Wrapper>
 )
}

Now you can use it like this

export default Page({ header: true, headerTitle: 'header title' })(PageOne)
like image 70
Yury Tarabanko Avatar answered Sep 27 '22 00:09

Yury Tarabanko