Ben Edelstein Founder @LogRocket, formerly @Google.

Tips for styling React apps in JavaScript

1 min read 433

While many developers still use CSS to style their React apps, writing styles in JavaScript has become an increasingly popular practice as it gives all of the conveniences of CSS preprocessors without the need to learn a new language.

Most CSS-in-JS libraries involve creating a JavaScript object of styles. As an example, this is what a style object looks like using my preferred library, Aphrodite.

const styles = StyleSheet.create({
  container: {
    position: 'relative',
    width: 40,
    height: 50,
  },
)}

Variables

Many best practices from SASS/LESS workflows still apply when using JavaScript styles. Colors fonts, and other constants can be stored as variables, which can be used like so:

// colors
const YELLOW = '#FFF83C';
// fonts
const BOLD = 700;
const TIMES_NEW_ROMAN = '"Times New Roman", Georgia, Serif';
// shared constants
const border = `1px solid ${YELLOW}`;
const styles = StyleSheet.create({
  textBox: {
    color: YELLOW,
    fontFamily: TIMES_NEW_ROMAN,
    fontWeight: BOLD,
    border, 
  },
)}

New ES6 language features come are handy for sharing styles cleanly. In the above example, border is referenced with the object literal shorthand notation.

Use JS objects in place of mixins

The spread operator (…) is particularly useful when defining a commonly-used sequence of styles (in this example the rules needed to add an ellipsis to overflowing text).

const textEllipsis = {
  whiteSpace: 'nowrap',
  textOverflow: 'ellipsis',
  overflow: 'hidden',
  width: '100%',
};
const styles = StyleSheet.create({
  textBox: {
    ...textEllipsis,
    backgroundColor: 'gray',
  },
)}

Create helper functions for more complex motifs

More complicated sequences of rules can be abstracted behind helper functions. For example, when styling placeholder text, I use a function that returns an object of styles:

const getPlaceholderStyles = obj => ({
  '::-webkit-input-placeholder': obj,
  '::-moz-placeholder': obj,
  ':-ms-input-placeholder': obj,
  ':-moz-placeholder': obj,
  ':placeholder': obj,
});
const styles = StyleSheet.create({
  input: getPlaceholderStyles({ color: RED }),
)}

Be consistent about naming schemes

One of biggest advantages of writing styles in JavaScript is that classNames are scoped to each component by default. This means that conventions like BEM are unnecessary. Still, it is helpful to be consistent with a naming scheme for classNames. For example, I use container for the outermost className of each React component.

Check out cool JS libraries

There are lots of helpful libraries for creating JavaScript styles. One that I particularly like is called color and handles common color manipulations:

You come here a lot! We hope you enjoy the LogRocket blog. Could you fill out a survey about what you want us to write about?

    Which of these topics are you most interested in?
    ReactVueAngularNew frameworks
    Do you spend a lot of time reproducing errors in your apps?
    YesNo
    Which, if any, do you think would help you reproduce errors more effectively?
    A solution to see exactly what a user did to trigger an errorProactive monitoring which automatically surfaces issuesHaving a support team triage issues more efficiently
    Thanks! Interested to hear how LogRocket can improve your bug fixing processes? Leave your email:

    Full visibility into production React apps

    Debugging React applications can be difficult, especially when users experience issues that are difficult to reproduce. If you’re interested in monitoring and tracking Redux state, automatically surfacing JavaScript errors, and tracking slow network requests and component load time, try LogRocket.

    LogRocket is like a DVR for web apps, recording literally everything that happens on your React app. Instead of guessing why problems happen, you can aggregate and report on what state your application was in when an issue occurred. LogRocket also monitors your app's performance, reporting with metrics like client CPU load, client memory usage, and more.

    We made a custom demo for .
    No really. Click here to check it out.

    The LogRocket Redux middleware package adds an extra layer of visibility into your user sessions. LogRocket logs all actions and state from your Redux stores.

    Modernize how you debug your React apps — .

    import Color from 'color';
    const styles = StyleSheet.create({
      button: {
        backgroundColor: RED,
        ':hover': {
          backgroundColor: new Color(RED).lighten(0.2).string(),
        },
      },
    )}

    Helpful Resources


    Ben Edelstein Founder @LogRocket, formerly @Google.

    Leave a Reply