Styling React Apps with JavaScript: A Growing Trend

As the React ecosystem continues to evolve, more developers are turning to JavaScript for styling their apps. This approach offers the benefits of CSS preprocessors without requiring knowledge of a new language. In this article, we’ll explore the advantages of writing styles in JavaScript and provide tips for implementing this method.

Creating Style Objects

Most CSS-in-JS libraries involve creating a JavaScript object of styles. For example, using the Aphrodite library, a style object might look like this:

javascript
const styles = {
container: {
backgroundColor: '#f0f0f0',
padding: '20px',
},
};

Variables and Constants

Many best practices from SASS/LESS workflows still apply when using JavaScript styles. Colors, fonts, and other constants can be stored as variables and used throughout your code. New ES6 language features, such as object literal shorthand notation, make it easy to reference these variables.

Sharing Styles Cleanly

The spread operator (...) is particularly useful when defining a commonly used sequence of styles. For example, you can create a helper function that returns an object of styles for adding an ellipsis to overflowing text.

Helper Functions for Complex Motifs

More complicated sequences of rules can be abstracted behind helper functions. For example, when styling placeholder text, you can use a function that returns an object of styles.

Consistent Naming Schemes

One of the biggest advantages of writing styles in JavaScript is that classNames are scoped to each component by default. While conventions like BEM are unnecessary, it’s still helpful to be consistent with a naming scheme for classNames.

Exploring JS Libraries

There are many helpful libraries for creating JavaScript styles. One popular option is the color library, which handles common color manipulations.

Error Tracking with LogRocket

Get set up with LogRocket’s modern React error tracking in minutes. Visit their website to sign up and receive an app ID. Then, install LogRocket via npm or script tag, and initialize it client-side.

Leave a Reply

Your email address will not be published. Required fields are marked *