Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How is a boolean a valid React.ReactNode value?

How is a boolean value (true or false) not an invalid value for a prop of type React.ReactNode, resulting in the following being a Typescript error?

interface IProps {
    node: React.ReactNode;
}

const foo: IProps = {
    node: false,
};

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

ReactNode represents all the possible values that can be put as a child of an element. Booleans are allowed because the following is a very common pattern for doing conditional rendering:

const condition: boolean = Math.random() > 0.5;

<div>
  {condition && (
    <p>You win!</p>
  )}
</div>

If condition is false, then the div’s children prop will be false, and so the type is set up to allow this.

If you only want to allow elements, consider using React.ReactElement instead:

interface IProps {
   node: React.ReactElement;
}

const foo: IProps = {
  node: <div /> // Good
}

const foo2: IProps = {
  node: null // Error. If you want to allow null, change to React.ReactElement | null
}

const foo3: IProps = {
  node: false // Error
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading