Home > Software design >  React.Children.map Typescript
React.Children.map Typescript

Time:08-14

Hi I've been having this issue for few hours and I couldn't figure out the correct type for the child inside the map. I tried using ReactElement but it gives me an error on the first parameter of React.Children.map()

{
    React.Children.map(children, (child: React.ReactElement, i) => {
            const id = child.props.children[0].props.id;
            console.log(id);
            return <div></div>;
        }
    )
}

When I try this code it's saying that

`Argument of type 'ReactNode' is not assignable to parameter of type 'ReactElement<any, string | JSXElementConstructor<any>> | readonly ReactElement<any, string | JSXElementConstructor<any>>[]'.ts(2345)`

I've added an image below been looking for the correct type if there is something maybe someone encountered this type issue? Thanks

Note: The error in the images is when I don't assign any type on child

enter image description here

enter image description here

CodePudding user response:

In short, the ReactNode type is a union type for a: ReactChild | ReactFragment | ReactPortal | boolean | null | undefined.

The type error is telling you what's wrong: You're assuming the child is always going to be defined AND is an JSXElement/ReactElement with props with an array of children that has a props property with a defined id prop.

VSCode, or rather the Typescript language server, is displaying an error stating that there's no way for it to know if a child meets these requirements because you haven't put up any type guards for them. Therefore, you can't access properties on this child parameter when it can be null, undefined, boolean, string, number, and so on.

I'm not sure what you're trying to accomplish with your code above, but you have to let Typescript know that only a child that Edit Typescript React Child Map

CodePudding user response:

Looks like i need to change the type of children to children: JSX.Element[] | JSX.Element; it didn't give me any error. ReactNode is not assignable to ReactElement

JSX.Element can be assigned to ReactElement

i think its because ReactNode could be anything. anyways thanks guys!

  • Related