React CSS modules

Last but not least, there is a great library that can help us work with CSS modules. You may have noticed how we were using a style object to load all the classes of the CSS, and because JavaScript does not support hyphenated attributes, we are forced to use a camelCased class name.

Also, if we are referencing a class name that does not exist in the CSS file, there is no way to know it, and undefined is added to the list of classes.

For these and other useful features, we may want to try a package that makes working with CSS modules even smoother.

Let's look at what it means to go back to the index.js we were using previously in this section with plain CSS modules, and change it to use React CSS modules instead.

The package is called react-css-modules, and the first thing we must do is install it:

  npm install react-css-modules

Once the package is installed, we import it inside our index.js file:

  import cssModules from 'react-css-modules';

We use it as an HoC, passing to it the Button component we want to enhance and the styles object we imported from the CSS:

  const EnhancedButton = cssModules(Button, styles);

Now, we have to change the implementation of the button to avoid using the styles object. With React CSS modules, we use the styleName property, which is transformed into a regular class.

The great thing about this is that we can use the class name as a string (for example, "button"):

  const Button = () => <button styleName="button">Click me!</button>;

If we now render the EnhancedButton into the DOM, we will see that nothing has really changed from before, which means that the library works.

Let's say we try to change the styleName property to reference a nonexisting class name, as follows:

  import React from 'react';
import { render } from 'react-dom';
import styles from './index.css';
import cssModules from 'react-css-modules';

const Button = () => <button styleName="button1">Click me!</button>;

const EnhancedButton = cssModules(Button, styles);

render(<EnhancedButton />, document.body);

We will see the following error in the console of the browser by doing so:

  Uncaught Error: "button1" CSS module is undefined.

This is particularly helpful when the codebase grows and we have multiple developers working on different components and styles.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.14.130.24