Destructuring assignment is a well known method for assigning default props to React components:
interface ButtonProps {
onClick: () => void;
disabled?: boolean;
getTextColor?: (theme: Theme) => string;
}
const Button = ({
onClick,
disabled = false,
getTextColor = (theme) => theme.primary
}: ButtonProps) => {
const theme = useTheme();
const computedTextColor = getTextColor(theme);
// Rest of logic
}
Suppose now that I want the getTextColor
prop to depend on the disabled prop:
// OPTION 1 (without changing getTextColor type)
const Button = ({
onClick,
disabled = false,
getTextColor = (theme) => disabled ? 'gray' : theme.primary
}: ButtonProps) => {
const theme = useTheme();
const computedTextColor = getTextColor(theme);
// Rest of logic
}
// OPTION 2 (change getTextColor to (theme: Theme, disabled: boolean) => void)
const Button = ({
onClick,
disabled = false,
getTextColor = (theme, buttonDisabled) => buttonDisabled ? 'gray' : theme.primary
}: ButtonProps) => {
const theme = useTheme();
const computedTextColor = getTextColor(theme, disabled);
// Rest of logic
}
Which of these two options is the "correct" way to achieve this sort of behavior OR is there a better way?