Is there a way to check or validate the props coming through directly from the related type or Interface

Advertisements

I have this simple component which takes as props an array of strings (tabs) and children (component to be rendered). I want to check if the provided children are of the same length as the tabs array directly from the type declaration or any cleaner way to handle this check.

type TabsProps = {
  tabs: string[];
  children: ReactNode | ReactNode[];
};

const Tabs = ({ tabs, children }: TabsProps) => {
  const [activeTab, setActiveTab] = useState(0);

  const componentsToRender = Children.toArray(children);
  
  //TODO Handle this check in a cleaner way
  if (componentsToRender.length !== tabs.length) {
    throw new Error('Your components or tabs are not of equal length');
  }

  const handleTabSwitch = (index: number) => {
    setActiveTab(index);
  };

  return (
    <TabWrapper>
      <TabHeader tabs={tabs} activeTab={activeTab} onTabSwitch={handleTabSwitch} />
      <Dividers />
      <TabContent>
        {componentsToRender.map((component, i) => {
          return activeTab === i ? component : null;
        })}
      </TabContent>
    </TabWrapper>
  );
};

export default Tabs;

As shown in the code snippet, I handled it with a simple if condition that throws an error
But I would rather it be handled while coding instead of at runtime

>Solution :

you can define a type that checks whether the length of the array of children matches the length of the array of tabs :

type TabsProps<T extends string[]> = {
  tabs: T;
  children: { [K in keyof T]: ReactNode };
};

const Tabs = <T extends string[]>({ tabs, children }: TabsProps<T>) => {
  const [activeTab, setActiveTab] = useState(0);

  const componentsToRender = Children.toArray(children);

  const handleTabSwitch = (index: number) => {
    setActiveTab(index);
  };

  return (
    <TabWrapper>
      <TabHeader tabs={tabs} activeTab={activeTab} onTabSwitch={handleTabSwitch} />
      <Dividers />
      <TabContent>
        {componentsToRender.map((component, i) => {
          return activeTab === i ? component : null;
        })}
      </TabContent>
    </TabWrapper>
  );
};

export default Tabs;

Leave a ReplyCancel reply