How to Add Multiple Browser Specific Values into a CSS Style in React

Line two divs side by side with CSS and React

Solution to bring new Newsbox component next to Coursebox

import Coursebox from './Coursebox';
import Newsbox from './Newsbox'
class ContainerRow extends React.Component {
render(){
return (
<div className='rowC'>
<Coursebox />
<Newsbox />
</div>
);
}
}

CSS

.rowC{display:flex; flex-direction:row;}

React.js inline style best practices

There aren't a lot of "Best Practices" yet. Those of us that are using inline-styles, for React components, are still very much experimenting.

There are a number of approaches that vary wildly: React inline-style lib comparison chart

All or nothing?

What we refer to as "style" actually includes quite a few concepts:

  • Layout — how an element/component looks in relationship to others
  • Appearance — the characteristics of an element/component
  • Behavior and state — how an element/component looks in a given state

Start with state-styles

React is already managing the state of your components, this makes styles of state and behavior a natural fit for colocation with your component logic.

Instead of building components to render with conditional state-classes, consider adding state-styles directly:

// Typical component with state-classes
<li
className={classnames({ 'todo-list__item': true, 'is-complete': item.complete })} />

// Using inline-styles for state
<li className='todo-list__item'
style={(item.complete) ? styles.complete : {}} />

Note that we're using a class to style appearance but no longer using any .is- prefixed class for state and behavior.

We can use Object.assign (ES6) or _.extend (underscore/lodash) to add support for multiple states:

// Supporting multiple-states with inline-styles
<li 'todo-list__item'
style={Object.assign({}, item.complete && styles.complete, item.due && styles.due )}>

Customization and reusability

Now that we're using Object.assign it becomes very simple to make our component reusable with different styles. If we want to override the default styles, we can do so at the call-site with props, like so: <TodoItem dueStyle={ fontWeight: "bold" } />. Implemented like this:

<li 'todo-list__item'
style={Object.assign({},
item.due && styles.due,
item.due && this.props.dueStyles)}>

Layout

Personally, I don't see compelling reason to inline layout styles. There are a number of great CSS layout systems out there. I'd just use one.

That said, don't add layout styles directly to your component. Wrap your components with layout components. Here's an example.

// This couples your component to the layout system
// It reduces the reusability of your component
<UserBadge
className="col-xs-12 col-sm-6 col-md-8"
firstName="Michael"
lastName="Chan" />

// This is much easier to maintain and change
<div class="col-xs-12 col-sm-6 col-md-8">
<UserBadge
firstName="Michael"
lastName="Chan" />
</div>

For layout support, I often try to design components to be 100% width and height.

Appearance

This is the most contentious area of the "inline-style" debate. Ultimately, it's up to the component your designing and the comfort of your team with JavaScript.

One thing is certain, you'll need the assistance of a library. Browser-states (:hover, :focus), and media-queries are painful in raw React.

I like Radium because the syntax for those hard parts is designed to model that of SASS.

Code organization

Often you'll see a style object outside of the module. For a todo-list component, it might look something like this:

var styles = {
root: {
display: "block"
},
item: {
color: "black"

complete: {
textDecoration: "line-through"
},

due: {
color: "red"
}
},
}

getter functions

Adding a bunch of style logic to your template can get a little messy (as seen above). I like to create getter functions to compute styles:

React.createClass({
getStyles: function () {
return Object.assign(
{},
item.props.complete && styles.complete,
item.props.due && styles.due,
item.props.due && this.props.dueStyles
);
},

render: function () {
return <li style={this.getStyles()}>{this.props.item}</li>
}
});

Further watching

I discussed all of these in more detail at React Europe earlier this year: Inline Styles and when it's best to 'just use CSS'.

I'm happy to help as you make new discoveries along the way :) Hit me up -> @chantastic

Applying style of multiple CSS classes using React CSS Modules

The reason the style wasn't being applied is because I had supplied the css 'active' class as a string value rather than as a reference from the imported CSS module:

import classes from "./RecipeSection.module.css";

Then I could supply the reference:

${classes.active}

The real clue was that in the initial generated html, my active class had not been allocated a hash as the recipe-section class had

<div class="RecipeSection_recipe-section__Asce8 active">

How to make React CSS import component-scoped?

It sounds like CSS Modules, or many of the other CSS-in-JS packages, does what you want. Others include Emotion (my current favorite), Styled Components, or many of the packages here.

A CSS Module is a CSS file in which all class names and animation names are scoped locally by default. All URLs (url(...)) and @imports are in module request format (./xxx and ../xxx means relative, xxx and xxx/yyy means in modules folder, i. e. in node_modules).

Here's a quick example:

Let's say we have a React component like:

import React from 'react';
import styles from './styles/button.css';

class Button extends React.Component {
render() {
return (
<button className={styles.button}>
Click Me
</button>
);
}
}
export default Button;

and some CSS in ./styles/button.css of:

.button {
border-radius: 3px;
background-color: green;
color: white;
}

After CSS Modules performs it's magic the generated CSS will be something like:

.button_3GjDE {
border-radius: 3px;
background-color: green;
color: white;
}

where the _3DjDE is a randomly generated hash - giving the CSS class a unique name.

An Alternative

A simpler alternative would be to avoid using generic selectors (like p, code, etc) and adopt a class-based naming convention for components and elements. Even a convention like BEM would help in preventing the conflicts you're encountering.

Applying this to your example, you might go with:

.aboutContainer {
# Some style
}

.aboutContainer__code {
# Some style
}

Essentially all elements you need to style would receive a unique classname.

How do I apply vendor prefixes to inline styles in reactjs?

React does not apply vendor prefixes automatically.

In order to add vendor prefixes, name the vendor prefix as per the following pattern, and add it as a separate prop:

-vendor-specific-prop: 'value'

becomes:

VendorSpecificProp: 'value'

So, in the example in the question, it needs to become:

<div style={{
transform: 'rotate(90deg)',
WebkitTransform: 'rotate(90deg)'
}}>Hello World</div>

Value prefixes can't be done in this way. For example this CSS:

background: black;
background: -webkit-linear-gradient(90deg, black, #111);
background: linear-gradient(90deg, black, #111);

Because objects can't have duplicate keys, this can only be done by knowing which of these the browser supports.

An alternative would be to use Radium for the styling toolchain. One of its features is automatic vendor prefixing.

Our background example in radium looks like this:

var styles = {
thing: {
background: [
'linear-gradient(90deg, black, #111)',

// fallback
'black',
]
}
};


Related Topics



Leave a reply



Submit