# Reacting to moods with icons

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?

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 = {
}

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>
)
}
}

• Thank you! This worked really well. Do you think it's a better way than the if-statement? – katjass Oct 24 '18 at 16:02
• @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. – Joseph Oct 24 '18 at 17:36