1
\$\begingroup\$

This is a class in my React app. This code works and displays an appropriate icon and question for every description.

class myQuestion extends PureComponent {
  render() {
    const { description } = this.props.question;
    let icon = icon;
    let question = question;
    if (description === 'Happy') {
      icon = <FontAwesomeIcon icon={faSmile} />;
      question = 'You answered happy. Why?';
    } else if (description === 'OK') {
      icon = <FontAwesomeIcon icon={faMeh} />;
      question = 'You answered OK. Why?';
    } else if (description === 'Angry') {
      icon = <FontAwesomeIcon icon={faAngry} />;
      question = 'You answered angry. Why?';
    } else {
      icon = '';
      question = '';
    }
    return (
      <div>
        <Question
          icon={icon}
          description={description}
          question={question}
        />
      </div>
    );
  }
}

I'd like to know how would be a better way to write this if else statement, preferably removing the let.

'description' is a prop of the question, but 'icon' and 'question' are dependent on what the 'description' is. The 'description' comes from the ID of a previous answer to a question.

Is there a way I could put this logic before the render function?

\$\endgroup\$
2
\$\begingroup\$

In cases where your value is determined by a string key, a key-value mapping is often the way to go. In this case, we store your icon JSX and questions in objects keyed by description. Then you simply access them using the current description as key.

const icons = {
  Happy: <FontAwesomeIcon icon={faSmile} />,
  OK: <FontAwesomeIcon icon={faMeh} />,
  Angry: <FontAwesomeIcon icon={faAngry} />
}

const questions = {
  Happy: 'You answered happy. Why?',
  OK: 'You answered OK. Why?',
  Angry: 'You answered angry. Why?'
}

class myQuestion extends PureComponent {
  render() {
    const { description } = this.props.question
    const icon = icons[description] || ''
    const question = questions[description] || ''

    return (
      <div>
        <Question
          icon={icon}
          description={description}
          question={question}
        />
      </div>
    )
  }
}
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Thank you! This worked really well. Do you think it's a better way than the if-statement? \$\endgroup\$ – katjass Oct 24 '18 at 16:02
  • \$\begingroup\$ @katjass It's better in a sense that I don't have to read through all conditional blocks to know what icon and question will be. Also, should you add more icons and questions, you simply add more to the lookups whereas in if-else, you'd be writing more code blocks. \$\endgroup\$ – Joseph Oct 24 '18 at 17:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.