Adding props to wrapped component with HOC

Viewed 161

I have this really simple component Test.js

import withProps from "./withProps"
function Test() {
  return <p>test</p>
}
export default withProps(Test)

The withProps function is a simple HOC that is adding a property 'test' with value 'ok' to this component

function withProps(Component) {
  return function (...props) {
    return <Component test="ok" {...props[0]} />
  }
}
export default withProps

Now for some reason when this component is inside a parent I can't see that added prop from the HOC only normal props

function App() {
  return <TestContainer>
           <Test test2="why?" />
         </TestContainer>
}
function TestContainer({ children }) {
  console.log(children.props); //can see test2 prop but can't see test prop added via HOC
}

Does somebody know a way to get this working or any proper way to do something similiar? Here's a demo of the problem you can play with

P.S. In the real situation the added props are computed height and width (based on other props of the wrapped component) and therefore I need them to be accessible from outside (for example the container using that component), I also need to do this without state because of SSR.

ANY HELP IS REALLY APPRECIATED

3 Answers

To me, it looks like withProps is creating an anonymous component embedding your real Test component. It means that if you want to see all the properties given to Test, you should look at the children of the children of TestContainer.

You'd need to use children.type.props to access test, while children.props will give you test2. If you need both props, you'll need to use this setup.

An HOC won't merge your props, as there's essentially two different components.

Related