DEV Community

loading...

Discussion on: React Clean Code - Simple ways to write better and cleaner code

Collapse
georgesofianosgr profile image
George Sofianos

Great post! I agree to all your suggestions excluding the second one. I find the ternary operator less readable than conditional rendering. Character ":" is difficult to notice between multiple lines. Why do you think that the ternary operator is the better option ?

Collapse
joaorafaelsantos profile image
João Santos

I agree. I've been refactoring several React components lately, and ternary operators (in my opinion) make the code noisy.

While two separate conditionals may indicate these pieces are not related, I think it's easier to read and understand.

Collapse
thawkin3 profile image
Tyler Hawkins Author

Thanks! Good question.

To me, the ternary helps show that these two pieces of UI are related. When true, you render X, and when false, you render Y.

    <div>
      <button onClick={handleClick}>Toggle the text</button>
      {showConditionOneText ? (
        <p>The condition must be true!</p>
      ) : (
        <p>The condition must be false!</p>
      )}
    </div>
Enter fullscreen mode Exit fullscreen mode

By splitting these out into two separate conditionals using the && operator, it obfuscates the fact that the two pieces of UI are related and that they are opposites of each other.

    <div>
      <button onClick={handleClick}>Toggle the text</button>
      {showConditionOneText && <p>The condition must be true!</p>}
      {!showConditionOneText && <p>The condition must be false!</p>}
    </div>
Enter fullscreen mode Exit fullscreen mode