I'm trying to implement a kind of React children components validation to have only specific components but facing an issue with type.
Please check out my code below:
// a component needs the validation
import { Children, FunctionComponent, isValidElement } from 'react';
import { AccordionProps } from '@components/old/signup/organisms/accordion/interfaces';
import CheckFormField from '@components/old/signup/organisms/checkFormField';
import AccordionHeader from '@components/old/signup/organisms/accordionHeader';
const Accordion: FunctionComponent<AccordionProps> = ({ children }) => {
const allowedComponents = [CheckFormField, AccordionHeader]; // these can only be children
Children.map(children, (child) => {
const childType = isValidElement(child) && child.type;
if (!allowedComponents.includes(childType)) { // here comes type error to use includes method
throw new Error('Error message..');
}
});
:
:
return (
<div>{children}</div>
);
The type error from above code:
TS2345: Argument of type 'string | false | JSXElementConstructor<any>' is not assignable to parameter of type 'FunctionComponent<CheckFormFiledProps> | FunctionComponent<AccordionHeaderProps>'. Type 'string' is not assignable to type 'FunctionComponent<CheckFormFiledProps> | FunctionComponent<AccordionHeaderProps>'.
and the props that I defined below:
// interfaces.ts
export interface AccordionProps {
children: ReactElement<any> | ReactElement[];
}
I suspect that the children prop above isn't probably proper type to make it but no luck to search it so far.
references:
only allow children of a specific type in a react component
Only allow specific components as children in React and Typescript
Thanks in advance.