D
D
djEban2022-03-24 17:43:21
typescript
djEban, 2022-03-24 17:43:21

How to inherit the props of a passed component in React?

Hello.

It is necessary that when a component is passed as a prop, its props are also inherited.
Example,

const Component: FC<ComponentProps> = ({ text }) => <></>;

const ComponentWrapper: FC<Type> = ({ component, ...rest }) => <Component {...rest} />

<ComponentWrapper component={Component} text="yes" /> // <---- надо,чтоб тут ТС унаследовал пропсы от Component


Tried to write this

type ComponentWrapper<T = {}> = {
  component: ComponentType<T>;
} & T;


But, of course, TS defines props as {}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander, 2022-03-24
@djEban

https://codesandbox.io/s/qna-q-1131330-55d4th

interface IWrapper<T> {
  component: T;
}

const Wrapper = <T extends React.ComponentType<any>>({
  component: Component,
  ...props
}: React.PropsWithChildren<IWrapper<T> & React.ComponentProps<T>>) => <Component {...props} />;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question