HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptreactCritical

Correct way to handle conditional styling in React

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
stylingwaycorrectreactconditionalhandle

Problem

I'm doing some React right now and I was wondering if there is a "correct" way to do conditional styling. In the tutorial they use

style={{
  textDecoration: completed ? 'line-through' : 'none'
}}


I prefer not to use inline styling so I want to instead use a class to control conditional styling. How would one approach this in the React way of thinking? Or should I just use this inline styling way?

Solution

If you prefer to use a class name, by all means use a class name.

className={completed ? 'text-strike' : null}


You may also find the classnames package helpful. With it, your code would look like this:

className={classNames({ 'text-strike': completed })}


There's no "correct" way to do conditional styling. Do whatever works best for you. For myself, I prefer to avoid inline styling and use classes in the manner just described.

POSTSCRIPT [06-AUG-2019]

Whilst it remains true that React is unopinionated about styling, these days I would recommend a CSS-in-JS solution; namely styled components or emotion. If you're new to React, stick to CSS classes or inline styles to begin with. But once you're comfortable with React I recommend adopting one of these libraries. I use them in every project.

Code Snippets

className={completed ? 'text-strike' : null}
className={classNames({ 'text-strike': completed })}

Context

Stack Overflow Q#35762351, score: 148

Revisions (0)

No revisions yet.