Reputation: 4681
Maybe the solution lies in the way that i declare the component:
import React, { FunctionComponent } from 'react';
export const ChapterDescription: FunctionComponent<
ChapterDescription
> = (
{
description,
name,
}: ChapterDescription,
) => (
<div>
<h3>{name}</h3>
<p>{description}</p>
</div>
);
When i was using only reactjs
for my components, i could easily do a conditionally render of a component like so (check if chapters
array has items and Only then render the component):
<OtherComponent/>
<div>
{chapters.length > 0 && <ChapterDescription
name={name}
description={description}
/>}
</div>
<OtherComponent2 />
When i try that in typescript is get the error:
Type 'false | Element' is not assignable to type 'Element'.
Type 'false' is not assignable to type 'Element'.ts(2322)
Is it bad practise any more to have conditional rendering ? How do i handle that case ?
Upvotes: 1
Views: 9542
Reputation: 4681
Well it is not so obvious but the fragments is the solution for the conditional rendering in typescript or one of the solutions:
Now it does not complain:
<Acomponent />
<>
{chapters && chapters.length > 0 && (
<ChapterDescription
name={selectedChapter.name}
description={selectedChapter.description}
/>
)}
</>
<AnotherComponent />
source: https://en.reactjs.org/docs/fragments.html
Upvotes: 14
Reputation: 1035
Try using ternary operator instead, that way you either use the component or null:
<OtherComponent/>
<div>
{chapters.length > 0 ? <ChapterDescription
name={name}
description={description}
/> : null}
</div>
<OtherComponent2 />
Upvotes: 0