Restrict the type of the children

Viewed 259

I am trying to build parent child component, that only children with specific type can be put into parent.

Here is the parent component definition:

export default function IdeaInfos(children: ReactElement<typeof IdeaInfo>) {
    const classes = useStyles()

    return (
        <Grid container
              justify="center"
              alignItems="center"
              className={classes.wrapper}>
            {children}
        </Grid>
    )
}

and child component definition:

export interface IdeaInfoProp {
    icon: string,
    text: string,
    textBgColor: string,
    alt: string
    reverse?: boolean,
}

const useStyles = makeStyles((theme: Theme) =>
    createStyles({
        text: {
            color: "#ffffff",
            textTransform: "uppercase",
            padding: theme.spacing(4),
            fontWeight: 700
        },
        mediaIcon: {
            height: "15rem",
            width: "15rem",
        },

    }),
)

export default function IdeaInfo({icon, text, textBgColor, alt, reverse = false}: IdeaInfoProp) {

    const classes = useStyles()

    return (
        <Grid item container xs={12} direction={reverse ? "row-reverse" : "row"}>
            <Grid item xs={12} md={6} style={{background: `${textBgColor}`}}>
                <Typography className={classes.text} variant="h4">
                    {text}
                </Typography>
            </Grid>
            <Grid
                item
                xs={12}
                md={6}
                container
                justify="center"
                alignItems="center"
            >
                <img src={icon} alt={alt} className={classes.mediaIcon}/>
            </Grid>

        </Grid>
    )

}

then I have tried to use as follows:

<IdeaInfos>
               <IdeaInfo alt="Avoid random ad"
                         icon={media}
                         text={random}
                         textBgColor="#99c1de"/>
           </IdeaInfos>

the compiler complains:

Type '{ children: Element; }' is missing the following properties from type 'ReactElement<({ icon, text, textBgColor, alt, reverse }: IdeaInfoProp) => Element, string | ((props: any) => ReactElement<any, string | ... | (new (props: any) => Component<any, any, any>)> | null) | (new (props: any) => Component<...>)>': type, props, key  TS2739

    68 |                 </Typography>
    69 |             </Typography>
  > 70 |            <IdeaInfos>
       |             ^
    71 |                <IdeaInfo alt="Avoid random ad"
    72 |                          icon={media}
    73 |                          text={random}

I am not sure, if the component IdeaInfos is defined correctly.

0 Answers
Related