Style a React Component

  • Creating and styling the Sidebar
  • CSS best practices

Creating a Sidebar component

Now that we finally a basic Webpack configuration ready, let's create a new Sidebar component and use our css-modules to style it.

$ mkdir app/components/Sidebar
$ touch app/components/Sidebar/{index.js,style.css}

Within this new component, we need to define our dependencies, create a placeholder component, then export that component wrapped in our styles.

import React from "react"
import cssModules from "react-css-modules"
import style from "./style.css"
export const Sidebar = () => {
return (
<div>
This is the sidebar
</div>
)
}
export default cssModules(Sidebar, style)

The third and fourth lines import our styles from our styles.css file and the cssModules function which allows us to export this component with its local styles. You'll see at the bottom of the file that, rather than simply exporting the Sidebar component, we are wrapping it in the cssModules function and pairing it with the styles that we imported above.

A note on relative vs. absolute paths: For the most part, we want to use absolute paths. Unfortunately, the coverage package we're going to use (Istanbul/nyc) does not sufficiently support the use of jsdom in favor of Karma (to be explained in a future lesson), so we will not be able to run webpack when running our tests, so for now, we will have to use relative paths.

Maintaining this consistency makes it much easier to move files around since if everything is absolute, you can merely find and replace. If on the other hand, everything is relative, you have to change the relative path all over your app, which can be a nightmare. Unfortunately, we do not have a choice at the moment, so we will use relative paths so we don't have to run our tests through webpack.

We want our Sidebar to look roughly like the image below:

image coming soon

We will use Flexbox for most of our alignment because it is now widely supported and much, much better than hacking away with tables. It's also the standard for React Native. If you break this Sidebar component down, you can see that our Sidebar is really a single column of fixed width which contains a list of contact cards.

image coming soon

We will eventually split these individual components into smaller pieces, but for now, we can just put them all under the single Sidebar component.

Let's start with something small:

...
export const Sidebar = () => {
return (
<div>
<h3>John Smith</h3>
<p>Last active: {Math.floor((Math.random() * 10) + 1)} minutes ago.</p>
</div>
)
}
...

In order to get this to render, we have to import this component into another component. Since we're going to want to render the Sidebar on on the root route, we should import it into our Home component.

...
import { default as Sidebar } from "../Sidebar"
export class Home extends React.Component {
render() {
return (
<div>
<Sidebar />
Home component
</div>
)
}
}
...

Now when you refresh your page, you'll see your Sidebar.

image coming soon

But it hardly looks like a sidebar... So now we need to style it.

Optional formatting for styles

There are several options when it comes to styling with react-css-modules. One is to import your styles and reference each style as a property of the style object.

.container {
background: red;
}
import React from "react"
import cssModules from "react-css-modules"
import style from "./style.css"
const HelloWorld = () => {
return (
<div className={style.container}>
Hello World!
</div>
)
}

Another option is the styleName reference that react-css-modules gives us. This allows us to use a string rather than an object reference. Because of the way components are wrapped using cssModules, you'll get better errors (compilation instead of runtime) when you mess up or forget to add a style.

const HelloWorld = () => {
return (
<div styleName="container">
Hello World!
</div>
)
}

That said, we're going to use the className with the style object because it's currently the most widely supported.

A note on using multiple classes for a single element: Don't do it. But if you must, you can set an option within react-css-modules to allow you to include multiple modules for a single element. Just be aware, once you start down the road of multiple class names, you start accumulating dead code that is time consuming and tedious to refactor out of your codebase.

Styling the Sidebar component

The first thing we should do is give our Sidebar a few className attributes so we can reference them in our style.css file:

...
export const Sidebar = () => {
return (
<div className={style.sidebar}>
<h3>John Smith</h3>
<p>Last active: {Math.floor((Math.random() * 10) + 1)} minutes ago.</p>
</div>
)
}
...

Then within our style.css file, add the classes that we will use to style our Sidebar:

.sidebar {
position: absolute;
left: 0;
top: 0;
height: 100vh;
width: 300px;
background: #eeeeee;
overflow-y: scroll;
border-right: 1px solid #ccc;
}

Most of this styling is straightforward. If you are not comfortable with Flexbox, I recommend checking out Flexbox Froggy, which is a game that will get you up to speed in about 10 minutes.

You may have noticed that our "Home component" text disappeared. That's because it's hidden behind the absolutely positioned Sidebar. Let's create a wrapper in our Home component that will eventually contain all of our chat messages.

import React from "react"
import cssModules from "react-css-modules"
import style from "./style.css"
import { default as Sidebar } from "../Sidebar"
export class Home extends React.Component {
render() {
return (
<div>
<Sidebar />
<div className={style.chatWrapper}>
Home component
</div>
</div>
)
}
}
export default cssModules(Home, style)

Then let's put 300px of margin on the left so that all of our content displays on the page.

Also note that you cannot use dashes (-) in the names of your styles when using object notation because JavaScript will interpret them as a mathematical expression. As it turns out, camelCase is already supported by CSS, so this shouldn't cause any problems over the long-run.

$ touch app/components/Home/style.css
.chatWrapper {
margin-left: 300px;
}

Additional

A note on nesting: Nesting your styles is generally considered bad practice. It makes refactoring harder and can lead to a lot of confusion. There are some exceptions.

Some people prefer to nest things like :hover or other pseudo-classes, as they could make it easier to understand the full functionality of a particular selector. This is also the case with nested @media queries, since it can be useful to quickly see which element is being affected by a particular media query. It's mostly a matter of preference, but the larger style guides tend to avoid nesting, so we will also avoid it.

Previous: Set Up Styles in WebpackNext: Snippets and Aliases