Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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,
};
like image 279
im1dermike Avatar asked Dec 19 '25 21:12

im1dermike


1 Answers

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
}
like image 139
Nicholas Tower Avatar answered Dec 22 '25 12:12

Nicholas Tower



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!