simplesample
simplesample

Reputation: 95

how to use unnecessary onClick event?

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>

Upvotes: 0

Views: 59

Answers (2)

rob.b
rob.b

Reputation: 119

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

Upvotes: 2

SirOneOfMany
SirOneOfMany

Reputation: 1084

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

Upvotes: 1

Related Questions