Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React - Received `false` for a non-boolean attribute 'attrName'

I have my own reusable Button component with the following code:

import React, {Component} from 'react';
import PropTypes from 'prop-types';

class Button extends Component {
    render() {
        const {href, border, children, className} = this.props;
        let baseClass = 'button';
        border && (baseClass += ' button-border');
        className && (baseClass += ' ' + className);
        return (
            href ? (
                    <a className={baseClass} {...this.props}><span>{children}</span></a>
                ) :
                (
                    <button {...this.props} className={baseClass}><span>{children}</span></button>
                )
        )
    }
}

Button.propTypes = {
    href: PropTypes.string,
    border: PropTypes.bool,
    className: PropTypes.string
}

Button.defaultProps = {
    border: false,
    className: ''
}

export default Button;

I'm then calling it in other components without the border prop, as I usually use it only for secondary type call to actions (please keep in mind the code is simplified just to illustrate the issue, so passing an additional className in order to avoid the warning is not a feasible solution).

I use the following code to call the button:

<Button>Continue</Button>

As you can see, there is no border prop specified, so the component is receiving the correct value from defaultProps: false.

Unfortunately after running my application I come across the following warning: react-dom.development.js:506 Warning: Received false for a non-boolean attribute border.

I have read multiple other questions with similar issue, but none of them were helpful.

In my implementation I also tried to amend the

border && (baseClass += ' button-border');

to

border ? (baseClass += ' button-border') : '';

but it didn't solve anything.

I also moved the Button.propTypes to static propTypes before the component render - without any result.

In terms of packages, I'm using: - react 16.8.2 - prop-types 15.7.2

Thanks for any leads on this.

like image 252
Entalpia Avatar asked Mar 05 '23 06:03

Entalpia


1 Answers

There's nothing wrong with how the component itself is defined (i.e. the defaultProps and propTypes on <Button />), however this is due to the following code, which is passed to both <a/> and <button/>.

{...this.props}

By doing so, we're passing border={false} to the native anchor and button elements, which is seemingly not supported, or at the very least will provoke an error from React. If you remove those lines, you'll note the error disappears; it might be worth explicitly passing down the props you'd like to these tags.

like image 161
lux Avatar answered May 16 '23 06:05

lux