Level Up Coding

Coding tutorials and news. The developer homepage gitconnected.com && skilled.dev && levelup.dev

Follow publication

CSS-in-JS: Pros and Cons of Styling in JavaScript

TUSHAR KANJARIYA
Level Up Coding
Published in
5 min readJul 25, 2023

CSS-in-JS: Pros and Cons of Styling in JavaScript | Tushar Kanjariya
CSS-in-JS: Pros and Cons of Styling in JavaScript

Table of Contents

Hello Developers 👋,
In recent years, the front-end development landscape has seen a rise in the popularity of CSS-in-JS solutions, where styles are written and managed within JavaScript code rather than in separate CSS files.

This approach has generated both enthusiasm and debate within the developer community. In this blog, we’ll explore the pros and cons of styling in JavaScript, also known as CSS-in-JS, to help you understand when and why you might consider using it in your projects.

👉 Pros of CSS-in-JS:

Here are some advantages of using the CSS-in-JS approach.

1️⃣ Scoped Styles and Avoiding Global Namespace Pollution:
One of the primary benefits of CSS-in-JS is the ability to scope styles to specific components.

Traditional CSS files often suffer from global namespace pollution, where class names or styles can accidentally clash or be affected by other parts of the application. With CSS-in-JS, styles are encapsulated within the components, ensuring that they only apply to the intended elements.

For Example:

import React from 'react';
import { css } from '@emotion/react';

const buttonStyles = css`
background-color: #3498db;
color: #ffffff;
padding: 10px 20px;
border: none;
border-radius: 4px;
cursor: pointer;
`;

const MyButton = () => (
<button css={buttonStyles}>Click Me</button>
);

2️⃣ Dynamic and Conditional Styling:
CSS-in-JS allows you to create dynamic styles based on props, state, or any other variables.

This flexibility is particularly useful for building responsive designs or theming applications based on user preferences.

For Example:

import React from 'react';
import { css } from '@emotion/react';

const dynamicButtonStyles = css`
background-color: ${props => props.primary ? '#3498db' : '#ffffff'}

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

No responses yet

Write a response