Every front-end developer knows about the normal ways to design a web application. Connect external stylesheet with an HTML file, apply classes and that’s it. However, many front-end developers don’t know that there are many other ways to customize the appearance of a web application built in React.
This is the standard approach for styling web applications in CSS. Linking React components with CSS files is pretty similar to how we do it in HTML. First we create a CSS stylesheet, write required CSS rules, and use the import statement to make it available in the React component.
Linking CSS files with React components is good if you’re already familiar with the process of writing CSS rules for styling web applications. Most web developers have been using this syntax for years.
Many React developers will advise against using inline styles, but there are certain use cases where they are useful. For example, if you are building a prototype of a web application, or just a small application.
A great thing about React web applications is that you can dynamically customize the appearance of each element. For example, if a user enters wrong value into the email field, change the color of input element to red and highlight the error.
In React, you can use expressions like ternary operators to set up a condition and dynamically return one class value or another. This is the best approach for setting an inline expression that generates a dynamic class value. The process is better described in this tutorial on setting conditional className values in React.
Alternatively, you can create a condition outside of JSX. This is better, because you can’t use statements like if, case or a for loop within JSX. You can set a much more complex condition outside of it.
React community has created various libraries for handling common styling tasks in React. For instance, the classnames package provides a function of the same name, used for dynamically applying class values.
There is also a popular styled-components package, which can help you create local CSS rules for components. It is commonly used in development of large scale web applications. You will often find that the knowledge of this package is necessary to get a job.