Home > Mobile >  How to pass a generic type in a React component props
How to pass a generic type in a React component props

Time:07-07

I have a component that takes an array of options which is defined as follows:

interface Props {
  options: {
    label: string;
    value: string;
  }[]
}
function MyComponent(props: Props) {...}

And implemented like this:

<MyComponent
  options={[
    { label: "Right Hand", value: "RIGHT" },
    { label: "Left Hand", value: "LEFT" }
  ]}
/>

In this example I give options to select a dominant hand and I've defined a type for that like this:

type DominantHand = "RIGHT" | "LEFT"

Is it possible to make MyComponent flexible to specify the type of options?

I've tried to accomplish this like the following but obviously the syntax isn't correct here:

type DominantHand = "RIGHT" | "LEFT"
type Gender = "MALE" | "FEMALE"

interface Props {
  options<T>: { // this syntax is wrong
    label: string;
    value: T;
  }[]
}
function MyComponent(props: Props) {...}

...

<MyComponent
  options<DominantHand>={[ // <--- this syntax is wrong
    { label: "Right Hand", value: "RIGHT" },
    { label: "Left Hand", value: "LEFT" }
  ]}
/>
<MyComponent
  options<Gender>={[ // <--- this syntax is wrong
    { label: "Male", value: "MALE" },
    { label: "Female", value: "FEMALE" }
  ]}
/>

Is there a way to accomplish this?

CodePudding user response:

After I have read the official typescript documentation I would suggest the following:

function MyComponent<T>(props: {
  options: {
    label: string;
    value: T;
  }[];
}) {
  return <div>MyComponent</div>;
}


type DominantHand = "RIGHT" | "LEFT";

function ParentComponent() {
  return (
    <MyComponent<DominantHand>
      options={[
        { label: "Right Hand", value: "RIGHT" },
        { label: "Left Hand", value: "LEFT" },
      ]}
    />
  );
};

CodePudding user response:

you should have the generic defined within the interface itself so it can be passed down to the object inside.

so it should be like this:

interface Props<T> {
  options: {
    label: string;
    value: T;
  }[]
}
function MyComponent(props: Props<string>) {...}

CodePudding user response:

Try with

interface Props<T> {
  options: <T>[]
}

And then you can create a seperate options object and pass it like this

interface GenericPropObject {
....
}

function MyComponent(props: Props<GenericPropObject>) {...}

CodePudding user response:

Try the following:

interface Props<T> {
  options: T[]
}
function MyComponent(props: Props<{test: string}>) {...}

Then, you can do this:

<MyComponent
  options={[{test: 'hello world'}]}
/>
  • Related