Update
Maybe the solution lies in the way that i declare the ponent:
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 ponents, i could easily do a conditionally render of a ponent like so (check if chapters
array has items and Only then render the ponent):
<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 ?
Update
Maybe the solution lies in the way that i declare the ponent:
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 ponents, i could easily do a conditionally render of a ponent like so (check if chapters
array has items and Only then render the ponent):
<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 ?
Share Improve this question edited May 27, 2020 at 15:16 Theo Itzaris asked May 27, 2020 at 15:02 Theo ItzarisTheo Itzaris 4,6815 gold badges44 silver badges75 bronze badges 1- Normally it's perfectly fine for children to be false. What type definition does that parent ponent have for its props (I think the ponent is "LesserContentColumn")? It may be restricting the types more than it should – Nicholas Tower Commented May 27, 2020 at 15:23
2 Answers
Reset to default 14Well 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 plain:
<Aponent />
<>
{chapters && chapters.length > 0 && (
<ChapterDescription
name={selectedChapter.name}
description={selectedChapter.description}
/>
)}
</>
<AnotherComponent />
source: https://en.reactjs/docs/fragments.html
Try using ternary operator instead, that way you either use the ponent or null:
<OtherComponent/>
<div>
{chapters.length > 0 ? <ChapterDescription
name={name}
description={description}
/> : null}
</div>
<OtherComponent2 />