Home > Blockchain >  React HoC usage with Typescript
React HoC usage with Typescript

Time:07-05

I have a react HoC where I have define few states and I am passing that to wrapped component. But the wrapped component itself has some props.

HoC.tsx

const HOC = (Component: React.ComponentType<T>) => {
  const [someState, setSomeState] = useState()

  const WrappedComponent = (props: T) =>
    return(
      <Component {(...props) as T} someState={someState}/>
    )

  return WrappedComponent
}

Hoc Usage in a component which needs other props

interfae NewComponentProps {
  x: number
}

const NewComponent: React.FC<NewComponentProps> = (props) => {
  let {x, someState} = props

  //Here I am not able to access someState prop which is coming from HOC, typescript is giving error
  return ( ... )
}

export default HoC(NewComponent)

How to handle such case and if I add someState in NewComponentProps interface it will work but I have to pass someState prop when I will call the NewComponent anywhere

So what should be the props type of new component to access both props??

CodePudding user response:

Here is a small example on how you might type it to make it work

type WrappedProps = {
  b: string;
};
// Here you type the child component as generic T combined with 
// your Wrapped props
const Wrapped = <T,>(Comp: ComponentType<T & WrappedProps>) => {
  return (props: T) => {
    return <Comp {...props} b="World" />;
  };
};

// ============================

type CompProps = {
  a: string;
};
// You need to manually pass the props of your component to the Wrapped
// function, because it can't infer the type
const Comp = Wrapped<CompProps>((props) => {

  // props now has the type CompProps & WrappedProps
  return (
    <p>
      A: {props.a}
      <br />
      B: {props.b}
    </p>
  );
});

// ============================

export default function App() {
  return <Comp a="Hello" />;
}
  • Related