Home > Mobile >  How to fix "Property htmlFor does not exist" on Custom React element?
How to fix "Property htmlFor does not exist" on Custom React element?

Time:11-11

I have this custom component :

import React from "react";
import classnames from 'classnames';

import { ButtonVariantColor } from '../types/button';

export type IconButtonProps = {
    element?: React.ElementType
    icon: React.ElementType
    variantColor?: ButtonVariantColor | string | undefined
} & React.HTMLAttributes<HTMLButtonElement & HTMLLabelElement>


export default function IconButton({ 
    className,
    element = 'button',
    icon,
    variantColor = ButtonVariantColor.default,
    ...props
}:IconButtonProps) {
    const Icon = icon;
    const ButtonElement = element;
    
    if (!(variantColor in ButtonVariantColor)) {
        variantColor = ButtonVariantColor.default;
    }

    return (
        <ButtonElement className={ classnames('btn btn-circle border-none text-base-content', {
            'bg-inherit hover:bg-gray-300 dark:bg-gray-800 dark:hover:bg-gray-700': variantColor === ButtonVariantColor.default,
            'bg-blue-200 hover:bg-blue-400 dark:bg-blue-900 dark:hover:bg-blue-700': variantColor === ButtonVariantColor.info,
            'bg-green-300 hover:bg-green-500 dark:bg-green-900 dark:hover:bg-green-700': variantColor === ButtonVariantColor.success,
            'bg-orange-200 hover:bg-orange-400 dark:bg-orange-700 dark:hover:bg-orange-500': variantColor === ButtonVariantColor.warning,
            'bg-red-200 hover:bg-red-400 dark:bg-red-900 dark:hover:bg-red-600': variantColor === ButtonVariantColor.error,
        }, className) } { ...props }>
            <Icon />
        </ButtonElement>
    );
};

and it is being used like this :

<IconButton element="label" icon={ ChevronLeftIcon } htmlFor={ menuId } />

However, htmlFor has an error and I don't know how to fix it. If the properties are inheriting from both HTMLButtonElement & HTMLLabelElement, why does it complain about htmlFor missing?

CodePudding user response:

How to fix "Property htmlFor does not exist"

tl;dr - HTMLAttributes does not include htmlFor prop.

HTMLAttributes resolves to AriaAttributes, DOMAttributes and common html attributes.. AriaAttributes stands for the accessibility properties and DOMAttributes stands for common properties for DOM elements (mostly handlers). htmlFor is not a common prop, it's unique only for Label element.

Solution: you should be using HTMLLabelElement type instead.

export type IconButtonProps = {
  ...
} & HTMLButtonElement & HTMLLabelElement;
  • Related