Reputation: 867
I created a simple HOC, which uses custom hook to track mouse position. I use the hook in the HOC function, and with it I want to pass that value to the wrapped component.
And that's OK, I pass the function as prop, and I can console.log that prop just with this.props
. I get the output {position: {…}}
in the console, as expected. When I expand that log object, I can see the output position: {x: 479, y: 396}
, which is exactly what I want.
But, when I want to access the actual object with this.props.position
, it just throws me an error:
TypeScript error in /Users/dvidovic/Projects/hooks-in-classes/src/components/HooksHOC.tsx(6,28):
Property 'position' does not exist on type 'Readonly<{}> & Readonly<{ children?: ReactNode; }>'. TS2339
Here's the HOC:
import React from 'react';
import { useMousePosition } from '../hooks/useMousePosition';
export const withHooksHOC = (Component: any) => {
return (props: any) => {
return <Component position={useMousePosition()} {...props} />;
};
};
And here's the wrapped component:
import React from 'react';
import { withHooksHOC } from './withHooksHOC';
class HooksHOC extends React.Component {
render() {
console.log(this.props); // this works
console.log(this.props.position); // this throws an error
return (
<div style={{ marginTop: '100px', fontSize: '72px' }}>Some text</div>
);
}
}
export default withHooksHOC(HooksHOC);
What do I have to change to access the position object?
Upvotes: 0
Views: 1398
Reputation: 5179
You need to pass a generic with an interface of your props to React.Component
:
interface HooksHOCProps {
position: {
x: number;
y: number;
}
}
class HooksHOC extends React.Component<HooksHOCProps> {
...
Upvotes: 2