Home > Enterprise >  how to use unnecessary onClick event?
how to use unnecessary onClick event?

Time:04-27

How to properly use unnecessary onClick events ?

interface IUIText {
    children: ReactNode;
    type: string;
    onClick?: (e: React.MouseEvent<HTMLDivElement>) => void;
}
const UIText = (props: IUIText) => {
    return (
        <div onClick={(e) => props.onClick(e)}> //Cannot invoke an object which is possibly 'undefined'.
            {props.children}
        </div>
    );
};

Usage:

 <UIText type={'solid'} onClick={e => clickHandler(e)}>Gallery</UIText>

But i can also use it without onClick event:

 <UIText type={'primary'}>Gallery</UIText>

CodePudding user response:

You can also do the check with a logical AND (&&)

interface IUIText {
    children: ReactNode;
    type: string;
    onClick?: (e: React.MouseEvent<HTMLDivElement>) => void;
}
const UIText = (props: IUIText) => {
    return (
        <div onClick={(e) => props.onClick && props.onClick(e)}> 
            {props.children}
        </div>
    );
};

CodePudding user response:

You will have to perform a null check. Your onClick is not 'unnecessary' but 'nullable'

interface IUIText {
    children: ReactNode;
    type: string;
    onClick?: (e: React.MouseEvent<HTMLDivElement>) => void;
}
const UIText = (props: IUIText) => {
    return (
        <div onClick={(e) => {
           if(props.onClick) props.onClick(e); // just check for onClick
        }}>
            {props.children}
        </div>
    );
};
  • Related