When using the React.ReactNode type for children if there are any inline conditional renders it will fail. I am currently using SWR to fetch data so I get an error like this:
Type 'false | void | Element | undefined' is not assignable to type 'ReactNode'. Type 'void' is not assignable to type 'ReactNode'
I'm not sure if previously React.ReactNode allowed void or if it was just silently missed due to implicit children before. Maybe this is an issue I should open up with React or SWR?
Previously
My React 17 Page component looked something like this previously. There is a lot of information around the breaking changes of implicit children but I always explicitly stated mine. Maybe a child of type: void, undefined, or null would be considered an implicit child though?
type PageProps = {
children: React.ReactNode
}
const Page = ({ children }: PageProps) = > {
return (
<div>
<Header />
<div>
{children}
</div>
<Footer />
</div>
)
}
export default Page
Problems
First Issue "multiple children were provided"
This JSX tag's 'children' prop expects a single child of type 'ReactNode', but multiple children were provided.ts(2746)
Fix
That's fixed simply enough with this type that allows multiple or single children. I do wish we could get away without being explicit about or many, but it does give stronger typing.
type PageProps = {
children: React.ReactNode[] | React.ReactNode;
};
Example Page Failing using SWR
const UsersPage: NextPage = () => {
const { data, error } = useSWR('/api/user', fetcher)
return (
<Page>
{users && (
<pre>
{JSON.stringify(users, null, 2)}
</pre>
)}
</Page>
)
}
This will give me the following error:
Type 'false | void | Element | undefined' is not assignable to type 'ReactNode'. Type 'void' is not assignable to type 'ReactNode'