DEV Community

Cover image for 👨‍💻 React from a Bootcamper's Perspective | Part 5 - 🎨 Styling Methods
Aaron Guyett
Aaron Guyett

Posted on

👨‍💻 React from a Bootcamper's Perspective | Part 5 - 🎨 Styling Methods

Styling in React can be confusing. It isn't hard to do, but there are a bunch of different ways to do it that are all acceptable. Working with static web pages taught me that inline styling was "frowned upon". A quick style.css file later, and I was moving along. React offers many different ways to style your single-page app (SPA), and I'll break them down with examples.


🖌️ Styling Overview 🖌️

No CSS or JS

I can think of five(ish) ways to style components in React:

  1. Stylesheets - Classic stylesheets in a .css, .scss, etc. format
  2. CSS Modules - A separate stylesheet with limited scope
  3. CSS Framework - Classes/Components that are used in-line
  4. JSS - JavaScript styles
  5. styled-components - CSS in JS

Stylesheets

Hopefully, you've worked with stylesheets by now. On CodePen, a stylesheet is provided with all pens. In react, the stylesheet is often placed in the same folder that the component or page is. For example:

Project
|
+-- src
| |
| +-- components
|   |
|   +-- Nav
|     |
|     +-- index.jsx
|         style.css

Enter fullscreen mode Exit fullscreen mode

The nav in our example would then import the style.css file by using import './style.css'. This approach allows the software engineer to work with stylesheets in classic fashion. Example below:

body {
  margin: 0;
}

.nav-button {
  color: blue;
}
Enter fullscreen mode Exit fullscreen mode

Stylesheets are easily optimizable by the browser and can be redone quickly, however, they can become long hard to maintain.

CSS Modules

CSS modules are similar to stylesheets because they are in the same location (see above file structure). They are imported differently and are scoped locally so are much better at separating styling code. The stylesheets are typically named different as well. Example: module.style.css. They are imported in a different manner in index.jsx: import styles from './module.style.css'.

They are accessed by using the styles object that is created from the stylesheet. The following example highlights how they are used.

import React from 'react';
import styles from './module.style.css';

const Nav = () => (
  <nav className={styles.navbar}>
    <span className={styles.link}>Home</span>
  </nav>
);

export default Nav;
Enter fullscreen mode Exit fullscreen mode

Each of the classes we created inside the modules can be accessed using dot notation. They are incredibly beneficial because there will no longer be styling conflicts due to the way the styles are scoped (locally), the CSS is exposed to JavaScript, and they are reusable. In turn, they are hard to mix with global CSS, lowerCamelCase must be used, and webpack is required.

CSS Frameworks

CSS Framework
There are a lot of CSS frameworks available. Each has documentation and some certain feature that it's known for. For example, Bootstrap is known for being a requirement among web developers on the Internet (search Bootstrap memes). There are tons of them available. Some of my favorite CSS frameworks are Bulma, Semantic, & Material UI. They are easy to use because they can be installed with a package manager and then imported globally or added to a file as needed.

import React from 'react';
import {
  Button,
  Container
} from 'react-bulma-components/full';

const Nav = () => (
  <Container>
    <Button color='danger' size='large' rounded outlined>Home</Button>
  </Container>
);

export default Nav;
Enter fullscreen mode Exit fullscreen mode

The above example shows how importing a component from a CSS framework allows you to use it as a component right in line. It comes pre-styled, but can be changed by adding modifier classes or updating the theme. We added some attributes to the Button component to make it rounded, large, red, and outlined.

CSS frameworks are easy to use, created with accessibility in mind, and quick to implement. They can be hard to optimize efficiently, may look unoriginal, and can increase the size of the app.

JSS

Similar to styled-components, JSS is created in the JS/JSX file. They are slightly more advanced than the other concepts we've covered but can be done. The example below showcases how JSS is used in React (as seen on the homepage of JSS found here).

import React from 'react'
import {render} from 'react-dom'
import {createUseStyles} from 'react-jss'

// Create your Styles. Remember, since React-JSS uses the default preset,
// most plugins are available without further configuration needed.
const useStyles = createUseStyles({
  myButton: {
    color: 'green',
    margin: {
      // jss-plugin-expand gives more readable syntax
      top: 5, // jss-plugin-default-unit makes this 5px
      right: 0,
      bottom: 0,
      left: '1rem'
    },
    '& span': {
      // jss-plugin-nested applies this to a child span
      fontWeight: 'bold' // jss-plugin-camel-case turns this into 'font-weight'
    }
  },
  myLabel: {
    fontStyle: 'italic'
  }
})

// Define the component using these styles and pass it the 'classes' prop.
// Use this to assign scoped class names.
const Button = ({children}) => {
  const classes = useStyles()
  return (
    <button className={classes.myButton}>
      <span className={classes.myLabel}>{children}</span>
    </button>
  )
}

const App = () => <Button>Submit</Button>

render(<App />, document.getElementById('root'))
Enter fullscreen mode Exit fullscreen mode

This approach allows easy theming and global styles that are only used when a component is mounted. The lazy stylesheets exist only as needed. The static elements of a stylesheet are shared between all elements. They offer local scoping but can be tough to learn and hard to read.

styled-components

I recently just finished (but never done) my new portfolio here: shameless plug. I utilized styled-components to create most of the components. The styled-components library can be installed with a package manager and then imported. The components are then built in the index.js(x) files using the library. An example from my portfolio is below.

import styled from 'styled-components';

export const Container = styled.div`
  max-width: 1280px;
  margin: 0 auto;
  width: 90%;
  @media (min-width: 601px) {
    width: 90%;
  }
  @media (min-width: 993px) {
    width: 80%;
  }
`;
Enter fullscreen mode Exit fullscreen mode

The above component is exported as Container and can be used as a component. It is rendered as a div. It is very easy to theme styled-components and SASS is accessible after installing. I used npm i styled-components and then began to work. There is a bit of a learning curve and performance may be impacted negatively but they were really cool to work with.

Bonus: In-Line Styling

<h1 style={{color: 'blue'}}>Hellow World</h1>


Conclusion

There are a lot of options available when choosing how to style your React SPA. It is important to understand each of the available styling methods in case you work on a project with one of them. Find one you like and get really good at it so you can become a styling snob. As always, see you next week. ~Aaron

Top comments (0)