Correct way to handle conditional styling in React

react conditional classname
react: change inline css conditionally based on component state
react style guide
conditional rendering react
best way to style react components
classnames
styled-components
react native conditionally change style

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?

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.

React, Dealing with CSS classes and the proper markup of your component (or React: basic componentization and conditional CSS styling This is software development, not only UI prototyping, and we all love the TDD process, don't we? By the way, we will start structuring our code for what's coming  Conditional rendering in React works the same way conditions work in JavaScript. Use JavaScript operators like if or the conditional operator to create elements representing the current state, and let React update the UI to match them. Consider these two components:

 <div style={{ visibility: this.state.driverDetails.firstName != undefined? 'visible': 'hidden'}}></div>

Checkout the above code. That will do the trick.

React: basic componentization and conditional CSS styling, How do I add CSS classes to components? Pass a string as the className prop: render() { return <span className="menu navigation-menu">Menu</span> }. Conditional rendering in React works the same way conditions work in JavaScript. Use JavaScript operators like if, and let React update the UI to match them. We use an if with our condition and

If you need to conditionally apply inline styles (apply all or nothing) then this notation also works:

style={ someCondition ? { textAlign:'center', paddingTop: '50%'} : {}}

In case 'someCondition' not fulfilled then you pass empty object.

Styling and CSS – React, How do you change the name of a class dynamically in react? As with many things in programming, there are many ways to implement conditional rendering in React. I’d say that, with exception of the first method (if/else with many returns), you’re free to choose whatever method you want. You can decide which one is best for your situation based on: Your programming style; How complex the conditional logic is

First, I agree with you as a matter of style - I would also (and do also) conditionally apply classes rather than inline styles. But you can use the same technique:

<div className={{completed ? "completed" : ""}}></div>

For more complex sets of state, accumulate an array of classes and apply them:

var classes = [];

if (completed) classes.push("completed");
if (foo) classes.push("foo");
if (someComplicatedCondition) classes.push("bar");

return <div className={{classes.join(" ")}}></div>;

ReactJS add dynamic class to manual class names, , just do some concatenation like we do in Javascript. You can use this npm package. Dealing with CSS classes and the proper markup of your component (or classNames from now on) can be sometimes frustrating, especially if we do it incorrectly from the very beginning by following a wrong approach. We will focus on a React component and we will use the Jed Watson’s classnames package.

I came across this question while trying to answer the same question. McCrohan's approach with the classes array & join is solid.

Through my experience, I have been working with a lot of legacy ruby code that is being converted to React and as we build the component(s) up I find myself reaching out for both existing css classes and inline styles.

example snippet inside a component:

// if failed, progress bar is red, otherwise green 
<div
    className={`progress-bar ${failed ? failed' : ''}`}
    style={{ width: this.getPercentage() }} 
/>

Again, I find myself reaching out to legacy css code, "packaging" it with the component and moving on.

So, I really feel that it is a bit in the air as to what is "best" as that label will vary greatly depending on your project.

lukeed/clsx: A tiny (229B) utility for constructing `className , In this tutorial, you will learn how to style your components in react. Also, you will discover how to conditionally apply styles based on the state of When you want to style many elements the same way, it is best to use we treat the imported styles like an object, containing all the defined classes as keys. There are four different options to style React components. All depend on your personal preferences and the specific complexity of your application. If you want to add just a few style properties, then inline styling is the best option. When you want to reuse your style properties in the same file then style-component are perfect.

How to use styles in React: Inline styles, CSS Modules & Styled , To get the best cross-browser support, it is a common practice to apply vendor prefixes to CSS properties and values that require them to work. For instance  Stack Overflow Public questions and answers; I want to style react-rte using a CSS file, but was unable to do so. Correct way to handle conditional styling in

React - Conditional style based on component state, One of the best ways is to use the prop to set a different class name inside the component. Then you can write some CSS that will display the  But I know that's not the right syntax. Isn't there a better way to do this? Correct way to handle conditional styling in React. Related. 2424. Add table row in

Applying Classes Conditionally in React, 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  There is no any particular rule that states to follow any specific type of styling. It’s one personal choice to follow a specific way of styling an React component.

Comments
  • I think you might have redux and react confused. Redux has nothing to do with styling.
  • i think your preference is spot-on for documents, but over-zealous for applications where markup interchange compat is not important. some major web apps are actually getting rid of classes and using only inline style, which is more predictable and easier to reason about than which of 5 applied rules is making the text bold. when the attribs are dynamic, you don't save much bandwidth like you do with repetitive documents. the app's semantics (view-source markup) are not that important either...
  • @rossipedia ah yes thank you, got mixed up, was looking at the redux tutorial when thinking about this, thank you!
  • If you aren't sure what the value of text-decoration will be because of the cascade and you only want to apply a line-through if complete is true, you'll have to build a style object. This way, you don't set it to none accidentally when it was another value. const style = { } if (complete) { style['textDecoration'] = 'line-through' }
  • Hey there, if you decided to use className as your conditional styling method. Without the classNames lib. I advise you to use undefined instead of null. The className property takes as input type a String or undefined - type(String | undefined) -- ⚡️
  • @JadRizk even better approach is to not set className at all if you don't have a valid value to set it to. const attrs = completed?{className:'text-strike'}:{} then <li {...attrs}>text to maybe strike</li> (spread operator). That way you don't set className at all unless you have a good value to assign. This is an important approach for setting some inline styles where you can't know what the current value is (because it could be set by CSS in a file you may not control).
  • @LinuxDisciple if all the fields evaluate to falsey then classnames just returns an empty string. This will not be affected by any CSS.
  • @DavidL.Walsh 21 hours ago I thought JadRizk's solution was a false choice between null and undefined that would still result in a no-value class attribute in the html (i.e. <p class></p> instead of <p></p>) so I provided a method that avoided setting className at all. As it happens I was wrong about JadRizk's solution. For the stated problem, I believe your solution with JadRizk's refinement is best. My syntax can set an arbitrary list of props and their values conditionally, but it's overkill for just setting a class name.
  • Was exactly looking for something like this. Conditional inline styling, thank you.
  • <div style={{ visibility: this.state.driverDetails.firstName !== undefined? 'visible': 'hidden'}}></div>. Small typo in ==.
  • Doesn't this pattern create an unnecessary diff though? My understanding of DOM diffing is that the style prop here would always change since in Javascript {} != {} If I'm correct about the diffing, perhaps it's better to use "undefined" instead of "{}"
  • Good note. I am not sure about this.
  • You should not combine classNames with style attribute, that's bit of a mess