简体   繁体   中英

How to add another prop to my Switch statement in React app

I have a React component based on a type prop I am returning jsx.

type Props = {
  variant: 'type-one' | 'type-two' | 'type-three';
  show: boolean;
};

const Placeholder = ({ type, show }: Props) => {
  switch (variant) {
    case 'type-one':
      return (
        <div id="type-one" className="type-one" />
      );
    case 'type-two':
      return (
        <div id="type-two" className="type-two" />
      );
    case 'type-three':
      return (
        <div id="type-three" className="type-three" />
      );
    default:
      return null;
  }
};

export default Placeholder;

How do I add the show prop here in a clean way? When show === true I want to show the specific <div> otherwise return null (nothing)


This is how the switch case works:

  1. The switch expression is evaluated once.
  2. The value of the expression is compared with the values of each case.
  3. If there is a match, the associated block of code is executed.
  4. If there is no match, the default code block is executed.

const Placeholder = ({ variant, show }: Props) => {
if(show){
  switch (variant) {
    case 'type-one':
      return (
        <div id="type-one" className="type-one" />
      );
    case 'type-two':
      return (
        <div id="type-two" className="type-two" />
      );
    case 'type-three':
      return (
        <div id="type-three" className="type-three" />
      );
    default:
      return null;
  }
}
else {
   return null;
  }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM