Ask Your Question
0

How can I pass components with certain props to a wrapper in React using TypeScript?

asked 2023-07-09 23:59:14 +0000

pufferfish gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2023-07-10 00:26:01 +0000

huitzilopochtli gravatar image

You can define a generic Props interface for the wrapper component and then use the Pick utility type to select only the props that match a certain interface. Here's an example:

import React, { ComponentType } from "react";

// define a generic Props interface for the wrapper component
interface WrapperProps<P> {
  component: ComponentType<P>;
  props: Pick<P, "propA" | "propB">; // use Pick to select only certain props
}

// define a component that takes a propA and a propB
interface MyComponentProps {
  propA: string;
  propB: number;
}

// create a component that will be wrapped
const MyComponent = ({ propA, propB }: MyComponentProps) => (
  <div>
    <p>{propA}</p>
    <p>{propB}</p>
  </div>
);

// create a wrapper component that passes propA and propB to the wrapped component
const Wrapper = <P extends {}>({ component: Component, props }: WrapperProps<P>) => (
  <Component {...props as P} />
);

// use the wrapper component to wrap MyComponent and pass only propA and propB
const App = () => (
  <Wrapper component={MyComponent} props={{ propA: "hello", propB: 123 }} />
);

In this example, we define a WrapperProps interface with two generic type parameters: P for the component's props, and W for any additional wrapper props (in this case, we only have component and props). We use the Pick utility type to select only the props that match the MyComponentProps interface, and then pass that to props in the Wrapper component. Finally, we use as P to assert that the props variable matches the component's expected props, and use the spread operator to pass those props to the Component.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-07-09 23:59:14 +0000

Seen: 10 times

Last updated: Jul 10 '23