Home > Software engineering >  How to pass a prop to a common component using react and typescript?
How to pass a prop to a common component using react and typescript?

Time:12-22

i want to pass a prop to reusable component using react and typescript.

what i am trying to do?

I have a reusable component named "ReusableComponent" which is used by 2 components namely

ComponentOne and ComponentTwo.

below is the code,

const SelectFieldWithQuery = <someProps>({
    fieldId,
    isMultiple,
    ...props
}: SelectFieldWithQueryProps<someProps>) => (
    <SelectWithQuery
        isMultiple={isMultiple}
    />
));



const ReusableComponent: React.FC<CustomSelectProps> = ({ fieldId }) => (
    <SelectFieldWithQuery
        options={{
            variables: { ordering: 'name', page: 1, pageSize: 1000 },
            notifyOnNetworkStatusChange: true,
            fetchPolicy: 'network-only',
        }}
        fieldId={fieldId}
        getOptions={({ data }) =>
            (data?.main?.data ?? []).map(({ name, id }) => ({
                label: name,
                value: id,
            }))
        }
        placeholder="Select option"
        useQuery={SomeQuery}
    />
);

const FirstComponent: React.FC<RouteComponentProps> = ({ history, location }) => {
    return (
        <ReusableComponent fieldId={fieldIdOne} />
    );
}

const SecondComponent: React.FC<RouteComponentProps> = ({ history, location }) => {
    return (
        <ReusableComponent fieldId={fieldIdTwo} />
    );
}

This works fine.

but now what i want to do is i have to set isMultiple on ReusableComponent within FirstComponent. if i add prop isMultiple to ReusableComponent like below

const ReusableComponent: React.FC<CustomSelectProps> = ({ fieldId }) => (
    <SelectFieldWithQuery
        options={{
            variables: { ordering: 'name', page: 1, pageSize: 1000 },
            notifyOnNetworkStatusChange: true,
            fetchPolicy: 'network-only',
        }}
        fieldId={fieldId}
        getOptions={({ data }) =>
            (data?.main?.data ?? []).map(({ name, id }) => ({
                label: name,
                value: id,
            }))
        }
        isMultiple //new line added
        placeholder="Select option"
        useQuery={SomeQuery}
    />
);

this works but adds isMultiple to SecondComponent as well. i want isMultiple prop to be applied to only FirstComponent. how can i do it.

could someone help me with this. thanks.

CodePudding user response:

You can add this field like this:

type CustomRouteComponentProps = RouteComponentProps & {isMultiple: boolean}
const FirstComponent: React.FC<CustomRouteComponentProps> = ({ history, location, isMultiple }) => { ... }

This way, in FirstComponent, you will have the union of RouteComponentProps and isMultiple, but not in SecondComponent

  • Related