CSS Empowerment with Emotion: Inline Styles vs. Styled Components in Vite React

sabin shrestha
readytowork, Inc.
Published in
6 min readSep 14, 2023
emotion and vite feature image

Introduction

Emotion CSS is a very powerful tool that enables developers to create dynamic styles that can change based on user interactions. In modern web development, the combination of Emotion CSS and Vite React has transformed our approach to styling. In this article, we dive into the world of Emotion CSS and its integration with vite React, Further we’ll discuss the dual pathways of styling approaches: inline styles and our styled components. As we delve into the article, we’ll examine their strengths, potential drawbacks, and real-world use cases. So buckle up now.

Emotion CSS and Vite React: A Distinct Collaboration

Before we start our journey through inline styles and styled components, let’s briefly understand the partnership between Emotion CSS and vite React and how to configure emotion in vite React. Emotion CSS, a CSS-in-JS library, harmoniously blends with Vite’s rapid build tool capabilities offering a distinct collaboration that has the potential to reshape how we approach styling. While they might not be the ultimate solution for every project, their unique attributes create an intriguing dynamic that developers can leverage for various scenarios.

Configuring Emotion CSS for Inline Styling in Vite React

Before we start the comparison of inline styles and styled components, let's set up Emotion CSS with a Vite React project. The configuration process for utilizing Emotion CSS’s inline styles is relatively straightforward. Here’s how to get started.

  1. Install Dependencies: Start by initializing a new Vite React project and navigating to its directory in the terminal. Then, install the required Emotion packages:
npm install @emotion/react @emotion/styled

With this you’ll have access to one of the styling approaches that Emotion provides i.e. Styled component. In order to be able to use inline styling there is something extra configuration you have to do first. For using CSS prop in the vite project first install @emotion/babel-plugin:

npm install -D @emotion/babel-plugin

we incorporate the @emotion/babel-plugin into the babel options of the @vitejs/plugin-react. Furthermore, in order to utilize the CSS prop, it's essential to instruct Vite to utilize Emotion's jsx function. This is achieved by configuring the jsxImportSource to point to @emotion/react.

import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";

// <https://vitejs.dev/config/>
export default defineConfig({
plugins: [
react({
jsxImportSource: "@emotion/react",
babel: {
plugins: ["@emotion/babel-plugin"],
},
}),
],
});

Now you can access the CSS prop, which enables you to use Emotion's inline styles in your Vite React project. As you proceed, we'll explore the benefits and drawbacks of this approach compared to styled components.

The Inline Styles Approach: Swiftness and Iteration

CSS props or inline styling are the primary ways to style elements with Emotion. They provide a concise and flexible API for styling your components. With this, developers can rapidly prototype and experiment with styles directly within components. The simplicity of this method eliminates the need for external stylesheets or class names, streamlining the development process. This approach is particularly advantageous for quick iterations, as changes are immediately reflected without the need for a browser refresh.

To gain hands-on experience with the inline styles approach in Emotion CSS and Vite React, let's embark on a practical journey by styling a button. This example will showcase the simplicity and immediate feedback loop that the approach offers.

  1. Component setup: Here we simply add a button element in our App component. Nothing complex.
function App() {
return (
<>
<button>Click me</button>
</>
);
}

export default App;
  1. Inline Styling: As we have already configured our react application to apply inline styles, we can use CSS props within the button JSX element. This prop allows us to define styles directly in the component’s JSX. Here In this example, we've used the css prop to define inline styles for the button and assigned it to the constant called button_css (To make code more readable and clean).
// packages
import { css } from "@emotion/react";

// constants
const text_color = "#fff";
const bg_color = "rgb(34, 139, 230)";
const bg_hover_color = "rgb(34, 139, 230, 0.8)";

// inline css with emotion
const button_css = css`
position: relative;
padding: 8px 16px;
background-color: ${bg_color};
font-size: 14px;
border-radius: 4px;
outline: none;
border: none;
color: ${text_color};

&:hover {
background-color: ${bg_hover_color};
}

&:active {
background-color: ${bg_color};
top: 1px;
}
`;

function App() {
return (
<>
<button css={button_css}>Click me</button>
</>
);
}

export default App;

Here is the result:

As you make changes to the inline styles, you’ll notice that the button’s appearance instantly responds to the adjustments. This real-time feedback encourages experimentation, as you can quickly fine-tune the visual aspects without leaving the component file.

Strength:

  • It's similar to the style prop but also has support for auto vendor prefixing, nested selectors, and media queries.
  • This approach also enables developers to bypass the styled API abstraction and directly style components and elements.
  • Inline styles expedite development by eliminating external files and classes.
  • Ideal for smaller projects or components where maintaining a separate stylesheet is overkill.
  • Encapsulation ensures that styles remain confined to the relevant component.

Drawbacks:

  • As styles are mixed with JSX, readability may suffer, especially in larger components.
  • Inline styles can clutter the component code, potentially making maintenance cumbersome.

The Styled Components Approach: Modular Elegance

For those who prefer using the styled. div API for component creation in React or are comfortable with styled components, this approach might be appealing. Styled components offer a structured methodology for styling within Emotion CSS. As these components can be utilized throughout the entire application, they facilitate modularity and separation of concerns for developers. By employing styled components, the codebase becomes more maintainable due to consistent design patterns applied across the application. This promotes both reusability and maintainability.

Now, let’s continue with the practical example of styling a button by using styled components.

  1. Component setup: In this step, we will create a new component named StyledButton and use the styled the method from Emotion to define its styling. We will pass the button HTML element as the styled component.
// packages
import styled from "@emotion/styled";

// constants
const text_color = "#fff";
const bg_color = "rgb(34, 139, 230)";
const bg_hover_color = "rgb(34, 139, 230, 0.8)";

// styled component
const StyledButton = styled.button`
position: relative;
padding: 8px 16px;
background-color: ${bg_color};
font-size: 14px;
border-radius: 4px;
outline: none;
border: none;
color: ${text_color};

&:hover {
background-color: ${bg_hover_color};
}

&:active {
background-color: ${bg_color};
top: 1px;
}
`;

function App() {
return (
<>
<StyledButton>I'm styled component</StyledButton>
</>
);
}

export default App;

This is the result:

By using the styled method, we created a new component with the same functionality as a regular button, but with the added benefit of having its own unique styles.

As you can see, the StyledButton component is defined by passing the button HTML element to the styled method. We then defined the styling using CSS-like syntax within a template literal. This approach offers clean and concise styling, with the added benefit of being reusable throughout the application.

Strength:

  • Styled components encapsulate styles and logic, enhancing code organization and reusability.
  • The separation of styles from JSX improves code readability, especially in complex components.
  • Styles can be based on component props and state, enabling versatile UI components.
  • Implementation of conditional and dynamic styling becomes effortless.

Drawbacks:

  • Styled components are not framework-independent, limiting their portability and adaptability to different environments.
  • The initial learning curve might be steeper for those new to-styled components.
  • As the project size grows, the size of styled components also increases. Generating numerous styled components can lead to larger bundle sizes.

Conclusion

In this article, as we traverse the landscape of Emotion CSS and its integration with Vite React, we discover the distinct advantages offered by the inline styles and styled component approaches. Both approaches have their unique strengths and drawbacks, and of course, choosing one over the other depends on the specific project requirements. If you want fast-paced iteration you should go with the inline styles approach and if you want more modularity, reusability, and maintainability in your project application then styled components are the best approach for you.

Ultimately it all depends on the developer’s preference, the project’s constraints, and the nature of the project. It's up to the developers to figure out the best approach for the project based on all these aspects. By embracing the strengths of both approaches, developers can confidently navigate the ever-evolving realm of web styling and create remarkable digital experiences.

I hope this helps! Let me know if you have any further questions.

--

--