Home  >  Q&A  >  body text

Analysis of the problem that optional boolean type props in React TypeScript are recognized as non-boolean types

I ran into a weird problem and I'm sure I'm missing something.

This is my Box function/component

export interface BoxProps extends React.HTMLProps<HTMLDivElement> {
    padding?: boolean
    stretch?: boolean
    flex?: boolean
    column?: boolean
    clickable?: boolean
    gap?: boolean
}

function Box (props: BoxProps) {
    return <div className={clsx(
        'flexbox',
        props.column && 'column',
        props.stretch && 'stretch',
        props.padding && 'padding',
        props.flex && 'flex',
        props.clickable && 'clickable',
        props.gap && 'gap',
        props.className
    )} {...props} />
}

Box.defaultProps = {

    padding: false,
    stretch:  false,
    flex:  false,
    column:  false,
    clickable:  false,
    gap:  false,
}

export default Box

All props are Boolean values, the default value is false, and they are all nullable (obviously)

But I still get the following warning on the console:

Warning: Received a false value for non-boolean property clickable.

I get this warning for every props

I don't understand how to create a component like this:

<Box gap stretch>{children}</Box> 等同于 <Box gap={true} ...

without receiving this warning.

I have tried many methods and may not be able to tell you every method.

P粉035600555P粉035600555226 days ago289

reply all(1)I'll reply

  • P粉128563140

    P粉1285631402024-03-30 11:07:26

    This is because the div element does not have these attributes (padding, gap, etc.).

    You should remove the {...props} part in your code. The modified code should look like this:

    function Box (props: BoxProps) {
        return <div className={clsx(
            'flexbox',
            props.column && 'column',
            props.stretch && 'stretch',
            props.padding && 'padding',
            props.flex && 'flex',
            props.clickable && 'clickable',
            props.gap && 'gap',
            props.className
        )} />
    }
    

    reply
    0
  • Cancelreply