CSS in a different dimension

CSS in a different dimension

ยท

5 min read

Hey everyone ๐Ÿ‘‹๐Ÿผ,

Today I will be talking about CSS-in-JavaScript. 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.

So what is this CSS-in-JS then?

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.

Ok! I know the meaning, the benefits, and when to use CSS-in-JS. So... when do we learn to use it?

tenor.gif

How to implement CSS-in-JS

You cannot use CSS-in-JS without CSS-in-JS libraries. There are a lot of CSS-in-JS libraries you can use but the most popular ones include:

Styled Components

Styled Components 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.

To use this library in a project, you should install it.

# with npm
npm install styled-components
or
# with yarn
yarn add styled-components

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!

Screenshot from 2021-08-13 00.29.41.png

JSS

JSS 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.

Installation

# using npm
npm install --save react-jss

# using yarn
yarn add react-jss
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;

Screenshot from 2021-08-13 00.20.34.png

Note: In JSS when styling you use commas to separate styles and styling of different elements.

Emotions

Emotion 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.

Let's quickly set this up ๐Ÿ˜

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

or

#with yarn
yarn add @emotion/styled @emotion/react
/** @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: .5s;   
  padding: 10px 20px;
  }
`;

const App = () => {
return(
  <div css={Wrapper}>
  <Title>Hello world!</Title>
  <Button>This is a button</Button>
</div>
)
};

Screenshot from 2021-08-13 23.03.19.png

Emotion has a similar syntax to styled-components.

Note: Emotion will not run if you don't include this comment on the top of the file line:

/** @jsx jsx */

Aphrodite

Aphrodite is another CSS-in-JS that has over 5.2k stars on Github

Here is how you install it:

#with npm
npm install aphrodite

How it works ๐Ÿ‘‡

import React, { Component } from 'react';
import { StyleSheet, css } from 'aphrodite';

const styles = StyleSheet.create({
    red: {
        backgroundColor: 'red'
    },

    blue: {
        backgroundColor: 'yellow'
    },

    hover: {
      background:'indigo',
        ':hover': {
            backgroundColor: 'purple'
        }
    },
    small: {
        '@media (max-width: 600px)': {
            backgroundColor: 'royalBlue',
        },
blue:{
  backgroundColor: 'green'
}
      }
    });
    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>

)
}
}

Screenshot from 2021-08-14 00.23.54.png

๐Ÿ˜… In Conclusion,

CSS-in-JS is a great alternative for styling your code instead of using the conventional .css files that we are accustomed to. That doesn't mean CSS-in-JS is a totally different way of styling, what it means is, it is an improved alternative of styling your code at the component level rather than the document level.