React::Different ways to style React components by CSS

There are a number of ways to style React components. Choosing the right method for styling components isn't a perfect absolute. It's a specific decision that should serve your particular use case, personal preferences, and above all, architectural goals of the way you work. 

Some of my goals in answering the question included covering these:
  •  global namespacing
  • dependencies
  • reusability
  • scalability
  • dead-code elimination
There seems to be a number of ways of styling React components used widely in the industry for production-level work.

  1. Inline CSS
  2. Normal CSS
  3. CSS in JS Libraries
  4. CSS Modules
  5. Sass & Scss
  6. Less
  7. Stylable
For each method, I’ll look at the need for dependencies, the difficulty level, and whether or not the approach is really a good one or not.

Inline CSS

  • Dependencies: None
  • Difficulty: Easy
  • Approach: Worst
I hope that everyone knows what is inline CSS and how to works. So I am not going to write details about it. In short, this is the CSS styling sent to the element directly using the HTML to JSX. You can include a javascript object for CSS in React components, although there are a few restrictions such as camel casing any property names which contain a hyphen. You can style React components in two ways using javascript objects as shown below.


import React from "react";
const spanStyles = {
  color: "#fff",
  borderColor: "#00f"
};
const Button = props => (
<button style={color:"#fff",borderColor:"#00f"}}><span style={spanStyles}>Button Name</span></button>
);
 

Regular CSS

  • Dependencies: None
  • Difficulty: Easy
  • Approach: Okay
Regular CSS is a common approach, arguably one step better than inline CSS. The styles can be imported to any number of pages and elements unlike inline CSS, which is applied directly to the particular element. Normal CSS has several advantages, such as native browser support(it requires no dependencies), there's no extra tooling to learn, and there's no danger of vendor lock-in.
You can maintain any number of style sheets, and it can be easier to change or customize styles when needed. But regular CSS might be a major problem if you're working on a bigger project with lots of people involved, especially without an agreed style guide for writing CSS.

Look like this below code.


/* styles.css */

a:link {
  color: gray;
}
a:visited {
  color: green;
}
a:hover {
  color: rebeccapurple;
}
a:active {
  color: teal;
}

import React from "react";
import "styles.css";

const Header = () => (
    <h2>Regular CSS </h2>
);

export default Header;

CSS-in-JS

CSS-in-JS is a technique that enables you to use JavaScript to style components. When this JavaScript is parsed, CSS is generated (usually as an <style> element) and attached to the DOM.
There are several benefits to this approach. For example, the generated CSS is scoped by default, meaning that changes to the styles of a component won't affect anything else outside that component. This helps prevent stylesheets from picking up bloat as time goes by; if you delete a component, you automatically delete its CSS.
Another advantage is that you can leverage the power of Javascript to interact with the CSS. For example, you can create your own helper functions in Javascript and use them directly in your CSS to modify the code.
Next, we'll look at two libraries that can be used to implement this in a React app.


1) JSS

  • Dependencies: react-jss
  • Difficulty: Easy
  • Approach: Decent
JSS bills itself as "an authoring tool for CSS which allows you to use Javascript to describe styles in a declarative, conflict-free and reuseable way".It's framework agnostic, but when it comes to styling React components, React-JSS integrates JSS with React using the new Hooks API.

The code looks like this


import React from "react";
import {render} from "react-dom";
import injectSheet from "react-jss";

// Create your styles. Since React-JSS uses the default JSS preset,
// most plugins are available without further configuration needed.
const styles = {
  myButton: {
    color: "green",
    margin: {
      // jss-expand gives more readable syntax
      top: 5, // jss-default-unit makes this 5px
      right: 0,
      bottom: 0,
      left: "1rem"
    },
    "& span": {
      // jss-nested applies this to a child span
      fontWeight: "bold" // jss-camel-case turns this into 'font-weight'
    }
  },
  myLabel: {
    fontStyle: "italic"
  }
};

// Define the component using these styles and pass it the 'classes' prop.
const Button = ({ classes, children }) => (
 <button classname="{classes.myButton}">
    <span className={classes.myLabel}>{children}</span>
  </button>
);

// Finally, inject the stylesheet into the component.
const StyledButton = injectSheet(styles)(Button);

const App = () => Submit
render(, document.getElementById('root'))

Styled-Components

  • Dependencies: styled-components
  • Difficulty: Medium
  • Approach: Decent
Styled-components is a further library that implements the above-mentioned CSS-in-JS technique. It utilizes tagged template literals — which contain actual CSS code between two backticks — to style your components. This is nice, as you can then copy/paste CSS code from another project (or anywhere else on the Web) and have things work. There’s no converting to camel case or to JS object syntax as with some other libraries.

Styled-components also removes the mapping between components and styles. As can be read in their documentation, this means that when you’re defining your styles, you’re actually creating a normal React component that has your styles attached to it. This makes your code more succinct and easy to follow, as you end up working with a <Layout> component, as opposed to a <div> with a class name of “layout”.

Props can be used to style styled components in the same way that they are passed to normal React components. Props are used instead of classes in CSS and set the properties dynamically.


Look like this below code.


  import React from "react";
import styled, { css } from "styled-components";

const Button = styled.button`
  cursor: pointer;
  background: transparent;
  font-size: 16px;
  border-radius: 3px;
  color: palevioletred;
  margin: 0 1em;
  padding: 0.25em 1em;
  transition: 0.5s all ease-out;
  ${props =>
    props.primary &&
    css`
      background-color: white;
      color: green;
      border-color: green;
    `};
`;

export default Button;

More information about Style-Component

Here is the link: style-component website link


Styled-Components Alternatives

There are a number of other CSS-in-JS libraries to consider depending on your needs. Some popular examples include:

Emotion is smaller and faster than styled-components. If you already use styled-components, you may not need to rush out and change libraries — its maintainers say it is closing the gap.
Linaria is a popular option for developers looking to maximize Core Web Vitals scores. Linaria’s core differentiator is that it’s a zero-runtime library — all of your CSS-in-JS is extracted to CSS files during the build.

CSS Modules

  • Dependencies: CSS-loader
  • Difficulty: Tough (Uses Loader Configuration)
  • Approach: Better
In the event that you’ve ever felt just like the CSS worldwide scope issue takes up most of your time once you got to discover what a specific style does, or in case getting freed of CSS records clears out you apprehensively pondering in the event that you might break something someplace else within the code base, I feel you.
CSS Modules solve this problem by making sure that all of the styles for a component are in one single place and apply only to that particular component. This certainly solves the global scope problem of CSS. Their composition feature acts as a weapon to represent shared styles between states in your application. They are similar to mixins in Sass, which makes it possible to combine multiple groups of styles.

Look like this below code:

import React from "react";
import style from "./panel.css";

const Panel = () => (
  <div className={style.panelDefault}>
    <div className={style.panelBody}>A Basic Panel</div>
  </div>
);

export default Panel;

//module css file
.panelDefault {
  border-color: #ddd;
}
.panelBody {
  padding: 15px;
}

Sass & SCSS

  • Dependencies: Node-Sass
  • Difficulty: Easy
  • Approach: Best
Sass claims that it is the most mature, stable, and powerful professional-grade CSS extension language in the world. It is a CSS preprocessor, which adds special features such as variables, nested rules, and mixins(sometimes referred to as "syntactic sugar") into regular CSS. The aim is to make the coding process simpler and more efficient. Just like other programming languages, Sass allows the use of variables, nesting, partials, imports, and functions, which add superpowers to regular CSS.
There are a number of ways that a Sass stylesheet can be exported and used in a React project. As you might expect, Create React App supports Sass out of the box. If you're using webpack, you'll need to use the Sass-loader, or you could just use the sass --watch command.

Look like this below code:


$font-stack: 'Open Sans', sans-serif;
$primary-color: #333;

body {
  font: 100% $font-stack;
  color: $primary-color;

More Information

Learn more about using and installing Sass with a variety of programming languages from their official documentation at Sass: Syntactically Awesome Style Sheets. If you want to try something out, there's a service called SassMeister -The Sass playground where you can play around with different features of Sass and SCSS.

Less 

  • Dependencies: less, less-loader
  • Difficulty: Easy
  • Approach: Good
Less(Leaner Style Sheets) is an open-source, dynamic preprocessor style sheet language that can be compiled into CSS and run on the client-side or server-side. It takes inspiration from both CSS and Sass and is similar to SCSS. A few notable differences include variables starting with an @ sign in Less and with a $ in Sass.

Look like this below code:


@pale-green-color: #4D926F;

#header {
  color: @pale-green-color;
}
h2 {
  color: @pale-green-color;
}

More Information

You can get started with Less from the official documentation, and there's LESSTESTER, a Less Sandbox that converts your Less code into CSS.

Stylable

  • Dependencies: stylable,@stylable/webpack-plugin
  • Difficulty: Difficult
  • Approach
If you're not the biggest fan of CSS-in-JS, then Stylable might be for you. It's a preprocessor that enables you to scope styles to components so they don't leak and clash with other styles elsewhere in your app. It comes with several handy features -such as the ability to define custom pseudo-classes - so that you can apply styles to your components based on state. It is also inspired by TypeScript, with the project's home page stating:
We want to give CSS a type system - to do for CSS what Typescript does for Javascript.
When it comes to integrating Stylable with React, they offer a handy guide. There's also the create-stylable-app project, which will initialize a React-based web application with Stylable as its styling solution.

Look like this below code:


@namespace "Example1";

/* Every Stylable stylesheet has a reserved class called root
that matches the root node of the component. */
.root {
  -st-states: toggled, loading;
}
.root:toggled { color: red; }
.root:loading { color: green; }
.root:loading:toggled { color: blue; }

/* CSS output*/
.Example1__root.Example1--toggled { color: red; }
.Example1__root.Example1--loading { color: green; }
.Example1__root.Example1--loading.Example1--toggled { color: blue; }
Thanks for reading

Post a Comment

0 Comments