简体   繁体   中英

How to pass a prop to a common component using react and typescript?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM