Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react hoc in typescript

I describe HOC as in this article: https://medium.com/@jrwebdev/react-higher-order-component-patterns-in-typescript-42278f7590fb

My code (HOC):

import * as React from 'react';
import Dropzone from 'react-dropzone'


export const addImage = <P extends object>(WrappedComponent: React.ComponentType<P>) => {
  return class extends React.Component {

    render() {

      return <Dropzone noClick onDrop={()=>{console.log('drop')}}>
        {({ getRootProps, getInputProps }) => (

            <div {...getRootProps()} onClick={()=>{console.log('aa')}}>
              <input {...getInputProps()} />
              <WrappedComponent {...this.props} />;
      </div>

        )}

      </Dropzone>

    }
  };
}

In other component:

addImage(<Img src={item} />)

In HOC error: '{ children?: ReactNode; }' is assignable to the constraint of type 'P', but 'P' could be instantiated with a different subtype of constraint 'object'

How to fix the error?

like image 920
Александр Кос Avatar asked Jun 14 '26 15:06

Александр Кос


2 Answers

I think you need to specify the type of the props of the class you're returning from addImage:

export const addImage = <P extends object>(WrappedComponent: React.ComponentType<P>) => {
  return class extends React.Component<P> { // <- The "<P>" is the missing part

That should get rid of the warning in your screenshot. But thereafter Alejandro Garcia Anglada is correct with all his comments about how exactly to then use the HOC.

like image 150
Yoni Gibbs Avatar answered Jun 16 '26 08:06

Yoni Gibbs


In your case you will need to wrap your component in this way.

  1. Having a reference to the react component you want to wrap:
const Image = ({ item }) => <Img src={item} />
  1. Passing the reference to the HOC with the argument. As you can see in your code above, your HOC is expecting a argument P and that argument is the type of the props you are passing to Image
type Props = {
  item: string
}

addImage<Props>(Image)
like image 37
Alejandro Garcia Anglada Avatar answered Jun 16 '26 08:06

Alejandro Garcia Anglada



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!