Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React pseudo selector inline styling

Tags:

css

reactjs

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)


Is there a reason you're not styling the pseudo selectors with your label-hover class like this? Or am I misunderstanding your question?

.label-hover {
   color: orange;
   opacity: 0.5;
}

.label-hover:hover {
   opacity: 1;
}

You can't style pseudo selectors with inline styling (CSS Pseudo-classes with inline styles), and I think using javascript to see if the element is hovered is an unnecessarily complicated and hackish way of doing it.