skip to Main Content

I’m using Select component by NextUI (the question is not about Next UI).

The Select component expects children with SelectItem component by NextUI.

This works:

export const Select: FC<SelectProps> = ({
  isInvalid = false,
  variant = "flat",
  children,
  ...rest
}) => {
  return (
    <NextSelect variant={variant} isInvalid={isInvalid} {...rest}>
      <SelectItem key={"1"}>Select item</SelectItem>
    </NextSelect>
  );
};

It works because the children includes SelectItem.
However, this won’t work:

export const AnotherComponent = () => {
  return <SelectItem key={"1"}>Select item</SelectItem>;
};

export const Select: FC<SelectProps> = ({
  isInvalid = false,
  variant = "flat",
  children,
  ...rest
}) => {
  return (
    <NextSelect variant={variant} isInvalid={isInvalid} {...rest}>
      <AnotherComponent/>
    </NextSelect>
  );
};

The error thrown is TypeError: type.getCollectionNode is not a function.
What’s the difference between the two approaches that causes the second one to fail?

2

Answers


  1. The other approach doesn’t work because you’re passing as a child an object of type ReactComponent instead of a SelectItem.
    Instead of passing a component, you could call the AnotherComponent as a function :

    <NextSelect variant={variant} isInvalid={isInvalid} {...rest}>
          AnotherComponent()
    </NextSelect>
    

    but it’s cleaner to create a function that could receive params and return a component of type SelectItem rather than a React component, like this :

    export function createItem(): SelectItem  {
      return <SelectItem key={"1"}>Select item</SelectItem>;
    };
    
    Login or Signup to reply.
  2. You can define the type of AnotherComponent as FC

    or

    Call AnotherComponent as function

    export const AnotherComponent = () => {
      return <SelectItem key={"1"}>Select item</SelectItem>;
    };
    
    export const Select: FC<SelectProps> = ({
      isInvalid = false,
      variant = "flat",
      children,
      ...rest
    }) => {
      return (
        <NextSelect variant={variant} isInvalid={isInvalid} {...rest}>
          {AnotherComponent()}
        </NextSelect>
      );
    };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search