Wed, 26 Jan 2022

How To Implement CSS In React

7Newswire
11 Jan 2022, 01:33 GMT+10

We have all heard people saying that presentation matters! This is very much true for anything presented to an end-user, and the same applies to the beautiful web pages we view every day while swimming in this vast ocean of web.

In the web pages or apps, we use, the styling part of development is done majorly using an almost two decades old language known as CSS (cascading style sheets). It is considered the cornerstone language of web development along with others like HTML and Javascript. CSS takes care of the presentation layer or the styling, or the look and feel of a web page or app.

Another very popular language for creating web projects nowadays is Javascript or JS, and one of the most used frontend libraries/frameworks in JS for web projects is React. Styling is also very important in the applications or pages created using React. Surprisingly, React is not very opinionated about how styling should be incorporated in its implementation.

So throughout the rest of the blog, we will be discussing some most used ways to implement styling or CSS in React projects.

1. CSS Stylesheets

This way is the oldest and one of the easiest ways to style components or pages in React. Here the user can either have a global level CSS file for the project or different CSS files for different functions in the project.

For example:

We can create a file like 'sample.css' and have a class defined there like '.class1', which can be used inside any component like blogHeading.jsx or blogContent.jsx. The design or presentation will work flawlessly for the components.

But this kind of approach can lead to a lot of code management issues. In small projects, the approach might work well, but in large projects, there are high chances that there will be class naming issues, and class naming duplicacy can lead to code clash and unexpected class (as per CSS specificity rules) to be applied to our components.

2. Inline Styling

Inline styling is an approach that works quite well for small projects and where we want some customized design for some specific code block, which might not be required for the entire project or at multiple places in the same project.

Here instead of making separate CSS files for the presentation layer logic, we declare the style variables in the JSX files only.

For example:

Instead of creating separate variables we can also pass the variable value in the style attribute of the JSX tag directly like

This type of styling or CSS in React usage is feasible only if we employ a style, which is to be used only one time or does not have very lengthy design semantics; otherwise, we should avoid using this approach.

3. CSS Modules

A modular code is always better from code maintainability, code readability, and usability perspective. CSS modules help us scope the CSS classes/animations (with the same names and otherwise) locally to the component or the file. CSS modules turn the CSS into locally scoped CSS for that file.

There is a convention which is followed for CSS modules to work as per expectations:

{component/fileName}.module.css. If we do not follow this pattern, then the CSS modules or the local scoping will not work.

For implementing CSS in React, CSS files are generated dynamically by the component's CSS modules, having dynamic class names for the styles. Like if we declare class 'divStyle' in 2 different CSS files for two components (say Comp1 and Comp2), then post project build, the class name for the components might be like :

  • Class name for component 1 (Comp1) class divStyle : Comp1_divstyle_123123
  • Class name for component 2 (Comp2) class divStyle : Comp2_divstyle_768768

For example:

Local scoping helps in avoiding name clash issues. CSS Modules is not an official specification or an implementation in the browser. It is rather a process in the build process like Webpack or Browserify.

Usage of 'composes' and @extend gives extensibility and implementation of DRY to the CSS modules approach for design implementation.

4. CSS In JS

CSS in JS libraries gives us a different and new approach to implement CSS in JS React projects. Some libraries like Radium are framework-specific (built for React), and some are framework agnostic like Aphrodite, Emotion, and Styled components. Here we will discuss 'styled components' on a high level.

Styled components help us to write the CSS inside our JS code only. Styled components' main thought is to have completely styled standalone components and reuse them in the entire application whenever and wherever required. So the styling is also done at a component level only. The components can run independently without relying on any external CSS.

CSS in JS React solves name clash, dependency, incorrect class load issues for components.

For example:

Here we can see the Styled Link JSX tag has its style declared in the JSX file only and does not rely on any other CSS class for its styling. So whenever we render the StyledLink tag (in this file, or can be used as a standalone component), it will have the same style as declared above.

A similar approach is also followed by libraries like Aphrodite, Emotion, Radium, as previously mentioned too. Below are some examples of the same:

1. Aphrodite:

Aphrodite is a framework-agnostic CSS-in-JS. With 4K stars, it works with or without React and provides powerful features such as injecting styled into the Dom, auto prefixes styles and more. It uses the class attribute to transform everything into classes.

Source

2. Emotion:

Implementation in Emotion can be done either by using @emotion/styled or @emotion/react libraries. With 4.2K stars, it allows you to style apps with string or object styles and also has predictable composition to avoid specificity issues with CSS.

Below is the example for @emotion/react implementation.

Source

3. Radium:

Radium is a set of powerful tools to manage inline styles on React elements without CSS. Created by Formidable Labs, it has 6.5K stars and allows bundling up styles with the React components, coupling javascript, HTML, and styling together. You can style your components based on the state of your app by its props-based rendering mechanism.

Source

Now, after declaring a 'Button' element using the style defined in JS, we can render the < Button> component wherever we want, and the styling will be taken care of by Radium.

5. Utility First CSS

Utility first CSS is the approach where the non-semantic way of using the CSS is encouraged, not the semantic way, while using CSS with React. Here the naming of classes is handled by the utility first frameworks like Bootstrap, Tailwind.

Helper classes for margins, padding, text, display style, border size, responsive behavior, etc., are given to the user. The naming and name clash issues are not at all a worry point in this approach.

This approach limits a custom CSS's flexibility, but they help speed up the development time and give us beautifully styled webpages in no time.

Example showing the creation of blue-colored Button, which can be hovered upon and has rounded corners.

6. CSS Preprocessors: SASS/LESS

Sometimes writing CSS code can be cumbersome for large applications. As sometimes, there might be an implementation of CSS where the code can not be reused, leading to many code repetitions. Apart from that, the use of braces and the semicolon in the CSS syntax can be too much work from a developer's perspective.

There can not be a generalization or conditional flow in a normal CSS file. To save the developers from this nightmare, there are CSS preprocessors, which allow the developers to write CSS code in a more developer-friendly and reusable format, which is then compiled into normal CSS code for the browser or web server. Many CSS preprocessors to choose from but mostly used are SASS (syntactically awesome style sheets) and LESS (leaner style sheets). We will discuss SASS at a high level here.

CSS Preprocessors - Sass vs LESS vs Stylus (With Examples)

SASS or CSS preprocessors, for that matter, provide the developer with a lot of advantages over normal inline or CSS stylesheet implementation in a project, like:

  • Declaration of variables and loops in the CSS code for reusability and avoiding code rewriting
  • Conditional statements
  • Mixins and inheritance for reusability
  • Partials using _{filename}.sass/scss and @extends to avoid code duplication
  • Operators for running basic arithmetic among the style values

There is no need to use braces and semicolons in SASS files. Only proper indentation works for styling the components.

For example (below example shows the way variables can be declared in SASS, which in turn helps in code reusability and better readability.

Source

Please check: Detailed Guide To CSS Supports In Browsers

Conclusion

So, no one implementation would do wonders for a React project. Choice of implementing CSS in a React project depends on various factors like code size, project extensibility, scale, and use case.

Any production-grade React project runs on multiple devices and browsers. The user might land up in CSS compatibility issues, as developers might write code by keeping one browser or a device in mind, but this might create an issue for a widely used application or page.

To mitigate any risks of CSS cross browser/device compatibility, we highly recommend testing your web applications using the awesome cross browser compatibility testing utility provided by LambdaTest.

I hope this blog has given you a high-level overview of the different approaches for using CSS with React in your project. Please let us know in the comments if you have any questions or want to discuss any concept in detail.

More Pittsburgh News

Access More

Sign up for Pittsburgh News

a daily newsletter full of things to discuss over drinks.and the great thing is that it's on the house!