⊗jsrtPmSyInr 97 of 112 menu

Ways to style React components

There are many different ways to style React components. Here we will cover some of the main ones.

The standard approach we can use, as with regular web page styling, is to use global CSS. Here we create one external common CSS file with styles. With this approach, all class names are in the global scope, which can lead to conflicts between them. You can also make many small CSS files. This approach is ineffective when creating large scalable applications.

The next approach is inline styling, using it we can add CSS styles inline, similar to how it is done in regular HTML. In this case, we will work with the style attribute, passing it the necessary CSS properties. Using such styling is considered bad form and is recommended only for adding styles that are dynamically calculated during rendering. This method is good for quickly prototyping the interface of a separate component.

The next couple of methods we'll look at are modern, increasingly popular, and effective styling methods. These are the methods that are recommended for styling large, scalable React applications.

The first of them is the use of the library Styled Components, which uses template strings for styling. This method allows us to write regular CSS in JS code, using all its functionality.

The second way is to use CSS modules. In this case, a CSS module is a CSS file in which, by default, all class and animation names are in the local scope, i.e., they are only available within the component that uses it.

In these last two methods we can not be afraid of conflicts between class names, because they are unique - the concept of local scope is used. Also, when using them, there is no need for the BEM methodology.

In the following lessons we will look at all the methods given here in more detail.

enru