test

} export default withProps(Test) " /> test

} export default withProps(Test) " /> test

} export default withProps(Test) "/>

Adding props to wrapped component with HOC

1.1k Views Asked by At

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

There are 3 best solutions below

1
Harshad Prajapati On

As I know, HOC will be triggered once it's initiated to render. At that time your props passed through HOC are available

In your example, you are trying to read props from HOC which is not rendered yet.

I added log to make you sure to know about the process of rendering https://codesandbox.io/s/dazzling-hofstadter-z7f9j0?file=/src/Test.js

Also, you can check the example for HOC here https://stackblitz.com/edit/preact-hoc?file=index.js

0
Stéphane Veyret On

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.

2
rschristian On

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.