0
\$\begingroup\$

I wrote some conditionals for a button component and everything works, but I feel like this is not the right way of writing conditionals. Would appreciate it if anyone could review my code.


import buttonStyles from './Button.module.scss';
import { Link } from "gatsby";

interface Props {
  content: string,
  color: string,
  path?: string,
  type: string
}

export default function Button(props: Props): JSX.Element {
  const availableColors = ['blue', 'grey', 'dark-grey', 'white'];
  const borderColors = [''];

  if(!availableColors.includes(props.color)) {
    console.error(`"${props.color} color key not available for button style`);
    return;
  }

  if(!props.content) {
    console.error(`"${props.content} is not valid as content`);
    return;
  }

  let buttonStyle = buttonStyles[`button--${props.color}`];
  let elementType;

  if(props.type == 'link' || props.type == 'button') {
    if(props.type == 'link') {
      elementType = <Link to={ props.path } className={ buttonStyle }>{ props.content }</Link>
    } else {
      elementType = <button className={ buttonStyle }>{ props.content }</button>
    }
  } else {
    console.error(`"${props.type} is not valid as a type. Use 'link' or 'button'`);
    return;
  }

  return (
    <React.Fragment>
      { elementType }
    </React.Fragment>
  );
}
```
\$\endgroup\$
3
  • 5
    \$\begingroup\$ Does this answer your question? How can I re-write the conditionals for this button (It's basically the same question by the same OP) \$\endgroup\$ – CertainPerformance Oct 23 '20 at 14:19
  • \$\begingroup\$ Thankyou! It answers my question. \$\endgroup\$ – pochini Oct 29 '20 at 21:11
  • \$\begingroup\$ When an answer solves your problem, you may consider marking it as Accepted (check the checkbox on the left) to indicate that the issue is resolved :) \$\endgroup\$ – CertainPerformance Oct 29 '20 at 21:34

Browse other questions tagged or ask your own question.