React Cookbook
上QQ阅读APP看书,第一时间看更新

Styling a component with CSS classes and inline styles

In the last recipe, we learned how to create a class component. Now let's add some CSS to our Home component.

In React, one of the best practices is to have the style file in the same directory as the component. If you have worked with PHP, Node, or any other server language, you probably write your styles in a style.css file, and you include it using a link tag in your template. React uses Webpack, which is the most popular module bundler at the moment. With Webpack, we can configure the way that we want to handle our styles (using CSS directly or by using a CSS preprocessor such as Sass, Stylus, or Less CSS), and with Webpack we can implement CSS modules. This is a powerful way to avoid the three main issues of CSS:

  • No more conflicts (unintentional CSS overwrites)
  • Explicit dependencies (styles per component)
  • No global scope

In Chapter 10Mastering Webpack 4.x, we will cover Webpack, and we'll be able to implement CSS modules using Sass or Stylus in our project.