Reputation: 1
Im trying to create a wrapper class that simply returns children props
type Props {
children: any;
}
const Wrapper: = ({ children }: Props) {
//some logic
return children;
}
Curios if it exist a more specific type than any
for this purpose? If i try something like ReactNode
or JSX.Element
i can no longer pass multiple children. On the other hand by using a fragment, the linter complains because children
may also be a single element.
const Wrapper: React.FC = ({ children }) => {
return <>{children}</>;
}
Any thought appreciated!
Upvotes: 0
Views: 4176
Reputation: 976
Use React.PropsWithChildren
function Wrapper({
prop1,
children
}: React.PropsWithChildren<{ prop1: string }>) {
return <>{children}</>;
}
Upvotes: 1
Reputation: 187014
React.ReactNode
is the correct type of the children
prop of React components. And React components must return a JSX.Element
.
These are not the same type.
children
may be a list, and react components must return a single node. So you just have to wrap children
in a fragment to guarantee you always get a single JSX.Element
.
type Props = {
children: React.ReactNode;
}
const Wrapper = ({ children }: Props) => {
//some logic
return <>{children}</>;
}
// works
const test1 = <Wrapper>123</Wrapper>
const test2 = <Wrapper>
<>foo</>
<>bar</>
</Wrapper>
Upvotes: 2
Reputation: 2161
You can cast the children prop to a type that satisfies the return type of React.FC
const Wrapper: React.FC = ({ children }) => {
return children as React.ReactElement;
}
Upvotes: 0