idlackage
idlackage

Reputation: 2863

How to use withRouter() with a generic component

I have a component like this:

function GenericComponent<T>(props: RouteComponentProps) {
    ...
}

export default withRouter(GenericComponent)

When attempting to use it with <GenericComponent<SomeModel> />, I get the following error:

Expected 0 type arguments, but got 1.

How do I pass T to withRouter?

Upvotes: 1

Views: 307

Answers (1)

tmhao2005
tmhao2005

Reputation: 17504

Generally you can't do that way, I think you can do by having a function working as a factory with takes generic T then return the component with that type as following:

function GenericComponent<T>(props: RouteComponentProps<T>) {
  // ...
}

export function factory<T>() {
  return withRouter((props: RouteComponentProps<T>) => (
    <GenericComponent<T> {...props} />
  ));
}

// Usage
function App() {
  const FooWithId = factory<{ id: string }>();

  return (
    <FooWithId />
  )
}

Upvotes: 1

Related Questions