New Sep 19, 2024

Passing function with arguments as a prop and invoking it internally in React

Libraries, Frameworks, etc. All from Newest questions tagged reactjs - Stack Overflow View Passing function with arguments as a prop and invoking it internally in React on stackoverflow.com

I got a Badge component in my React app. The badge can be painted in different colors. In order to make it more universal i've decided to add a prop called getBadgeColor. The idea is to implement different functions for different needs. For example, in one scenario i need badges for loading statuses. So i implement the function getStatusBadgeColor that looks like this:

enum BadgeColors {
    RED = 'red',
    YELLOW = 'yellow',
    GREEN = 'green',
    BLUE = 'blue',
    INDIGO = 'indigo',
    PURPLE = 'purple',
    PINK = 'pink',
}

export type BadgeColor = typeof BadgeColors[keyof typeof BadgeColors];

export type getBadgeColor<T> = (value: T) => BadgeColor;

export const getStatusBadgeColor: getBadgeColor<TStatus> = (status: TStatus) => { switch (status) { case Statuses.STATUS_SUCCESS: return BadgeColors.GREEN; case Statuses.STATUS_ERROR: return BadgeColors.INDIGO; default: return BadgeColors.BLUE; } }

My Badge component looks like this.

interface BadgeProps<T> {
    label: string;
    color?: BadgeColor;
    getBadgeColor?: getBadgeColor<T>;
    value?: T
}

export const Badge = <T,>({ label, color, getBadgeColor}: BadgeProps<T>) => {

const colorValue = getBadgeColor ? getBadgeColor() : color

return ( <span className="..."> <svg className={cn('h-1.5', 'w-1.5', fill-${colorValue}-500)} viewBox="0 0 6 6" aria-hidden="true"> <circle cx={3} cy={3} r={3} /> </svg> {label} </span> ) }

I pass the function like this

<Badge label={record.status} getBadgeColor={() => getStatusBadgeColor(record.status)}  />

So the problem is basically that i can't invoke a function inside the Badge component without calling it with arguments. Is there is a way i can do it? I would appreciate any help

Scroll to top