1

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 ?

1
  • Normally it's perfectly fine for children to be false. What type definition does that parent component have for its props (I think the component is "LesserContentColumn")? It may be restricting the types more than it shouldCommentedMay 27, 2020 at 15:23

2 Answers 2

14

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

    0

    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 /> 
    2
    • now it says null | Element. The truth should be hiding in the way that i declare the component, i ll update my question. thanks.CommentedMay 27, 2020 at 15:13
    • does the error disappear if you remove these lines? I had situations where typescript was misidentifying the problem due to another problem in the class declarationCommentedMay 27, 2020 at 15:15

    Start asking to get answers

    Find the answer to your question by asking.

    Ask question

    Explore related questions

    See similar questions with these tags.