RalfiBahar
RalfiBahar

Reputation: 72

React - don't accept props in a certain way (Typescript)

I want to create a button component (as in an example, but I am asking it in a general matter), I want to create three states of the button primary, secondary and tertiary.

export interface ButtonProps {
    primary?: boolean;
    secondary?: boolean;
    tertiary?: boolean;
};

export const Button: React.FC<ButtonProps> = ({
    primary, 
    secondary, 
    tertiary
 }) => {
 if(primary){
    return(/*PrimaryButton*/);
 }
 else if(secondary){
    return(/*SecondaryButton*/);
 }
 else if(tertiary){
    return(/*TertiaryButton*/);
 }

I want my component to not accept the parameters if more than one of these parameters are given, for example:

<Button primary secondary />

Upvotes: 0

Views: 528

Answers (2)

Max
Max

Reputation: 4739

From React standpoint, you should instead make impossible states impossible

However your question is about Typescript rather than React best practives, and you want to have 3 mutually exclusive properties in a type. Use union type for that, e.g.

type ButtonProps =
  | {
      primary: boolean
    }
  | {
      secondary: boolean
    }
  | {
      tetriary: boolean
    }

if you have shared props between all the variants

type ButtonProps = { label: string; onClick: () => void } & (
  | {
      primary: boolean
    }
  | {
      secondary: boolean
    }
  | {
      tetriary: boolean
    }
)

Upvotes: 1

ChrisG
ChrisG

Reputation: 2948

If you only want to allow a single type, why not make it a single prop?


export interface ButtonProps {
  variant: 'primary' | 'secondary' | 'tertiary';
};

<Button variant="primary" />

Upvotes: 4

Related Questions