React Pseudo Selector Inline Styling

React pseudo selector inline styling

My advice to anyone wanting to do inline styling with React is to use Radium as well.

It supports :hover, :focus and :active pseudo-selectors with minimal effort on your part

import Radium from 'radium'

const style = {
color: '#000000',
':hover': {
color: '#ffffff'
}
};

const MyComponent = () => {
return (
<section style={style}>
</section>
);
};

const MyStyledComponent = Radium(MyComponent);

Update 04/03/2018

This has been getting a few upvotes lately so I feel like I should update it as I've stopped using Radium. I'm not saying Radium isn't still good and great for doing psuedo selectors, just that it's not the only option.

There has been a large number of css-in-js libraries since Radium came out which are worth considering. My current pick of the bunch is emotion, but I encourage you to try a few out and find the one that fits you best.

  • emotion - ‍ The Next Generation of CSS-in-JS
  • fela - Universal, Dynamic & High-Performance Styling in JavaScript
  • styled-jss - Styled Components on top of JSS
  • react-jss - JSS integration for React
  • jss - JSS is a CSS authoring tool which uses JavaScript as a host language
  • rockey - Stressless CSS for components using JS. Write Component Based CSS with functional mixins.
  • styled-components - Universal, Dynamic & High-Performance Styling in JavaScript
  • aphrodite - It's inline styles, but they work! Also supports styling via CSS
  • csx - ϟ A CSS-in-JS solution for functional CSS in functional UI components
  • styled-jsx - Full CSS support for JSX without compromises
  • glam - crazy good css in your js
  • glamor - css in your javascript
  • glamorous - React component styling solved with an elegant API, small footprint, and great performance (via glamor)
  • styletron - ⚡️ Universal, high-performance JavaScript styles
  • radium - Set of tools to manage inline styles on React elements.
  • aesthetic - Aesthetic is a powerful React library for styling components, whether it be CSS-in-JS using objects, importing stylesheets, or simply referencing external class names.
  • j2c - CSS in JS library, tiny yet featureful

(Source)

CSS Pseudo-classes with inline styles in react.js

In HTML & CSS

.testAfter::after {

content: "->"

}
<div class="testAfter">Something</div>    

Styling CSS pseudoclasses in React

react's inline styles don't support css pseudo-classes. Or media queries. You could either write plain css, or use a lib for that https://github.com/styled-components/styled-components

How to inline code pseudo css class :hover on react material-ui element?

I dug around the internet some more

https://mui.com/system/the-sx-prop/

<Paper sx={{
'&:hover': {
backgroundColor: "black",
},
}}>
</Paper>

CSS pseudo elements in React

Got a reply from @Vjeux over at the React team:

Normal HTML/CSS:

<div class="something"><span>Something</span></div>
<style>
.something::after {
content: '';
position: absolute;
-webkit-filter: blur(10px) saturate(2);
}
</style>

React with inline style:

render: function() {
return (
<div>
<span>Something</span>
<div style={{position: 'absolute', WebkitFilter: 'blur(10px) saturate(2)'}} />
</div>
);
},

The trick is that instead of using ::after in CSS in order to create a new element, you should instead create a new element via React. If you don't want to have to add this element everywhere, then make a component that does it for you.

For special attributes like -webkit-filter, the way to encode them is by removing dashes - and capitalizing the next letter. So it turns into WebkitFilter. Note that doing {'-webkit-filter': ...} should also work.

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



Related Topics



Leave a reply



Submit