Theo Itzaris
Theo Itzaris

Reputation: 4681

How to conditional render a compnent in react + typescript

Update

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)

enter image description here

Is it bad practise any more to have conditional rendering ? How do i handle that case ?

Upvotes: 1

Views: 9542

Answers (2)

Theo Itzaris
Theo Itzaris

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

Antoni Silvestrovič
Antoni Silvestrovič

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

Related Questions