Home > Software design >  How is a boolean a valid React.ReactNode value?
How is a boolean a valid React.ReactNode value?

Time:02-12

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,
};

CodePudding user response:

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
}
  • Related