how to dynamically pass props for dynamic components in react type script

36 Views Asked by At
const temp = [{component: Button, props:buttonProps}, {component: Input, props: inputProps},{component: Select, props: selectProps} ]
temp.map(cm=>{
   return(<div><cm.component {...cm.props}/>)
})

when I use the above loop for dynamic components rendered in react with type script, getting some prop type definition error

error: Type '{} | { label?: string | undefined; variant?: "link" | "primary" | "icon-only" | "borderless" | "inline" | "cta" | undefined; size?: "xl" | "lg" | "sm" | "md" | undefined; id?: string | undefined; ... 277 more ...; onTransitionEndCapture?: TransitionEventHandler<...> | undefined; } | ... 7 more ... | { ...; }' is not assignable to type 'never'.
  The intersection 'IntrinsicAttributes & ButtonProps & TagProps & SwitchProps & ToggleProps & BadgeProps & MessageBlockProps & AvatarProps & CardProps & ModalProps' was reduced to 'never' because property 'variant' has conflicting types in some constituents.
    Type '{}' is not assignable to type 'never'.
1

There are 1 best solutions below

0
jayatubi On

Not sure if this meet you're looking for.

Since the map couldn't make tsc to check each individual element in the tuple then we build a type safe tuple for it.

const Button: React.FC<{ a: number }> = () => <></>;
const Input: React.FC<{ b: number }> = () => <></>;
const Select: React.FC<{ c: number }> = () => <></>;

function pair<T extends React.FC<any>>(component: T, props: React.ComponentProps<T>) {
  return { component, props };
}

const temp = [
  pair(Button, { a: 0 }), 
  pair(Input, { b: 0 }), 
  pair(Select, { c: 0 })
] as const;

temp.map((cm) => {
  const Component = cm.component;
  return (
    <div key={Component.name}>
      // The `props` type has been guaranteed when the `temp` was built
      <Component {...(cm.props as any)} />
    </div>
  );
});