Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading