Open In App
Related Articles

How to use CSS in different dimension (CSS-in-JS) ?

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

CSS is awesome and easy to get started with, but front-end applications have been scaling at a massive and complex rate that doesn’t make the current CSS designed for the job. CSS-in-JS is a real deal and in many ways, is very much the best nowadays when it comes to building and styling applications on the web.

What is CSS-in-JS:

Just as the name implies, CSS-in-Javascript. It is still CSS but it leverages JavaScript capabilities. It uses JavaScript as a language to describe styles in a declarative and maintainable way.

Benefits of CSS-in-JS:

  1. It throws errors to help you avoid mistakes, including syntax, type, and undefined errors.
  2. It makes dead code easier to manage.
  3. It helps you take advantage of anything from the JavaScript ecosystem.
  4. You don’t have to maintain multiple CSS files.
  5. Many CSS-in-JS libraries offer performance improvement like critical CSS with no additional setup needed.

When to use CSS-in-JS: A beginner who just wants to create websites without a dynamic front-end might find the standard CSS the best option for styling. But for developers who are working on a component-heavy javascript project, CSS-in-JS is the best option for you.

To implement CSS in JS: We cannot use CSS-in-JS without CSS-in-JS libraries. There are a lot of CSS-in-JS libraries Let’s see how to use CSS in JS with the help of these libraries with examples.

Steps to Create the React Application:

Step 1: Create a React application using the following command:

npx create-react-app 

Step 2: Now, navigate to the ‘form’ folder by writing the below commands in the command prompt terminal.

cd foldername

 Project Structure:

The updated dependencies in package.json file will look like:

  "dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-jss": "^10.10.0",
"react-scripts": "5.0.1",
"styled-components": "^6.1.1",
"web-vitals": "^2.1.4",
}

1. Styled Components:

It is one of the most popular CSS-in-JS libraries presented on Github. It has 23K+ stars on GitHub. With styled-components, you create a normal React component with your styles attached to it. Styled-component has awesome features like no class name bugs, painless maintenance. The steps on how to work with styled-components is sown below:

Step 1: Install the required library using the following command in your terminal:

// with npm
npm install styled-components

Example: Write down the following code in the App.js file.

Javascript

import React from 'react';
import styled from 'styled-components';
 
const Title = styled.h1`
  font-size: 1.5em;
  text-align: center;
  color: hotpink;
`;
 
// The Title component will render
// an <h1> tag with some styles
 
const Wrapper = styled.div`
  padding: 4em;
  background: rebeccapurple;
`;
// The Wrapper component will render
// a <div> tag with some styles
 
const Paragraph = styled.p`
color: white;
 
// When styling classes you simply use
// an ampersand and you style your class
// just like you did with traditional CSS
 
& .text{
text-align: left;
 
}
&:hover{
  color:pink;
}`
 
// The paragraph component will render a
// <p> tag with some styles
 
const App = () => {
    return (
        <Wrapper>
            <Title>
                Styled Components
            </Title>
            <Paragraph className='text'>
                This is paragraph
            </Paragraph>
        </Wrapper>
    );
}
 
// Use Title and Wrapper like any other
// React component – except they're styled!

                    

Step 2: Run the code below in the terminal

npm start

Output: 

2. JSS:

It is one more library with more than 6k stars on GitHub. JSS is an authoring tool for CSS which allows you to use JavaScript to describe styles in a declarative, conflict-free, and reusable way. It consists of multiple packages: the core, plugins, framework integrations, and others. The steps on how to work with JSS is down below:

Step 1: Install the required library using the following command in your terminal:

// with  npm
npm install --save react-jss

or
// with yarn
yarn add react-jss

Example: Now write down the following code in the App.js file. Here is an example of how to style with CSS-in JS library JSS.

Javascript

import React from 'react';
import { createUseStyles } from 'react-jss'
 
const useStyles = createUseStyles({
    wrapper: {
        textAlign: 'center',
        width: '100%',
        padding: '50px',
        color: '#444',
    },
 
    title: {
        color: '#fd1a26',
        fontWeight: 400,
    },
});
 
const App = () => {
    const classes = useStyles()
    return (
        <div className={classes.wrapper}>
            <h1 className={classes.title}>Hello World</h1>
            <p className={classes.p}>This is a paragraph</p>
 
        </div>
    )
}
 
export default App;

                    

Step 2: Run the code below in the terminal

npm start

Output:

3. Emotion:

It is a CSS-in-JS library that is focused on application performance. It has more than 7.7K stars on GitHub. It provides powerful and predictable style composition in addition to a great developer experience with features such as source maps, labels, and testing utilities. The steps on how to work with emotion are down below:

Step 1: Install the required library using the following command in your terminal:

// with npm
npm install @emotion/styled @emotion/react

Example: Now the installation is done write down the following code in the App.js file. Here is an example of how to style with the CSS-in-JS library emotion.

Javascript

/** @jsx jsx */
import React from "react";
import { jsx, css } from "@emotion/react";
import styled from "@emotion/styled";
 
const Wrapper = css`
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100%;
  padding: 40px;
  color: #444;
  border: 1px solid #4800f4;
`;
 
const Title = styled.h1`
  color: #0d1a26;
  font-weight: 400;
`;
 
const Button = styled("button")`
  padding: 8px 15px;
  border: none;
  border-radius: 5px;
  background-color: #4800f4;
  color: #fff;
  font-size: 14px;
  cursor: pointer;
 
  &:hover {
    transition: 0.5s;
    padding: 10px 20px;
  }
`;
 
const App = () => {
    return (
        <div css={Wrapper}>
            <Title>Hello world!</Title>
            <Button>This is a button</Button>
        </div>
    );
};

                    

Step 2: Run the code below in the terminal

npm start

Output:

4. Aphrodite:

It is another CSS-in-JS that has over 5.2k stars on Github. Aphrodite is a framework-agnostic CSS-in-JS with support for server-side rendering, browser prefixing, and minimum CSS generation. This library great works with or without react. The steps on how to work with aphrodite are down below

Step 1: Install the required library using the following command in your terminal:

// with npm
npm install aphrodite

Example: Now the installation is done write down the following code in the App.js file. Here is an example of how to style with CSS-in-Js library aphrodite.

Javascript

import React, { Component } from 'react';
import { StyleSheet, css } from 'aphrodite';
 
const styles = StyleSheet.create({
    container: {
        width: '70%',
        padding: '20px',
        border: '1px solid #000',
    },
    red: {
        backgroundColor: 'red'
    },
 
    blue: {
        backgroundColor: 'yellow'
    },
 
    hover: {
        background: 'rebeccapurple',
        ':hover': {
            backgroundColor: 'hotpink'
        }
    },
 
    small: {
        ':hover': {
            backgroundColor: 'royalBlue',
        },
    }
});
 
class App extends Component {
    render() {
        return (
            <div>
                <p className={css(styles.red)}>
                    This paragraph is purple.
                </p>
 
                <p className={css(styles.hover)}>
                    This paragraph is indigo and
                    turns purple on hover.
                </p>
 
                <p className={css(styles.small)}>
                    This turns blue when the browser
                    is less than 600px width.
                </p>
 
                <p className={css(styles.red, styles.blue)}>
                    This is yellow.
                </p>
 
                <p className={css(styles.blue, styles.small)}>
                    This paragraph is white, turns blue
                    when the browser is less than 600px width.
                </p>
            </div>
        )
    }
}

                    

Step 2: Run the code below in the terminal

npm start

Output:



Last Updated : 12 Dec, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads