Different Ways to Write CSS in React
Published: 2023-07-30 17:50:38

Styling is an important part of designing engaging user interfaces in React apps. While there are several approaches to writing CSS in React, selecting the appropriate one can have a big impact on the maintainability and scalability of your project. In this article, we will look at various approaches for styling React components and analyze their benefits and drawbacks.
## Inline Styling
Inline styling involves adding CSS directly to the JSX elements within a component using the style attribute.
 
This is a very simple example of inline style in React:

```javascript
const MyComponent = () => {
  const myStyle = {
    color: 'blue',
    fontSize: '16px',
    fontWeight: 'bold',
  };

  return (
    <div style={myStyle}>
      This text is styled using inline CSS.
    </div>
  );
};
```
**Pros:**

- Styles can be applied directly to particular elements.

- Styles can be changed dynamically based on status or props.

**Cons:**

- This violates the idea of separation of concerns.

- Complex styles are very difficult to manage and maintain.

- Code duplication and limited reusability.

## CSS Modules
CSS Modules provide a way to locally scope CSS in React components. Each CSS file is transformed into a unique class name, ensuring that styles only affect the specific component.

The beautiful thing about CSS modules is that they work with both SASS and regular CSS. Additionally, Create React App users can start using CSS modules right away with no setup required.

A CSS Module stylesheet is similar to a regular stylesheet, only with a different extension (e.g. styles.module.css). Here’s how they’re set up:

1. Make a file with the extension ".module.css."
2. Import the module into the React application, as we previously saw.
3. Add a className to an element or component and reference the particular style from the imported styles.

```javascript
/* styles.module.css */
.myComponent {
  color: red;
  font-size: 18px;
}
import styles from './styles.module.css';

const MyComponent = () => {
  return (
    <div className={styles.myComponent}>
      This text is styled using CSS Modules.
    </div>
  );
};

```
**Pros:**

1. Local scoping prevents styles from affecting other components.
2. makes it possible to use conventional CSS syntax and functionalities.
3. provides a tidy and well-organized style method.

**Cons:**

1. It Can cause the amount of CSS files to rise.

2. Name conflicts in bigger projects are still a possibility.

## Styled Components
Styled Components is a third-party toolkit that enables you to create reusable custom HTML components with specified CSS properties and use them anywhere you choose inside your project. For more[ info vist](https://styled-components.com/docs/basics)

The core of this library is a new feature called template literal that was added in ES6 version and lets you design your own string interpolation rules. To generate Styled Components, utilize this template literal together with CSS.
Here is an example:

```javascript
import styled from 'styled-components';

const StyledDiv = styled.div`
  color: green;
  font-size: 20px;
`;

const MyComponent = () => {
  return (
    <StyledDiv>
      This text is styled using Styled Components.
    </StyledDiv>
  );
};
```
**Pros:**
1. Promotes component-focused authoring techniques.

2. Creative styling with props.

3. Handles vendor prefixing automatically.

**Cons:**
1. Requires the installation of an additional library.
 
2. Developers that are unfamiliar with CSS-in-JS may have a learning curve.

## CSS-in-JS Libraries 
CSS-in-JS has accomplished something similar with CSS, just like React enabled us to write HTML as JavaScript using JSX.

We can write CSS styles directly in the javascript (.js) files for our components thanks to CSS-in-JS.

Not only can you create CSS style rules without creating a single.css file, but these styles may also be applied to specific components.

CSS-in-JS has accomplished something similar with CSS, just like React enabled us to write HTML as JavaScript using JSX.

We can write CSS styles directly in the javascript (.js) files for our components thanks to CSS-in-JS.

Not only can you create CSS style rules without creating a single.css file, but these styles may also be applied to specific components.

```css
import styled from "styled-components";

const Button = styled.button`
  color: limegreen;
  border: 2px solid limegreen;
  font-size: 1em;
  margin: 1em;
  padding: 0.25em 1em;
  border-radius: 3px;

  &:hover {
    opacity: 0.9;
  }
`;

export default function App() {
  return (
    <div>
      <Button>Click me</Button>
    </div>
  );
}
```
**Pros:**
1. built-in theming support, making it convenient to switch between different visual themes in the application.
2. Some libraries handle vendor prefixing automatically
3. Server-Side Rendering (SSR) Friendly.

**Cons:**
1. Adoption of CSS-in-JS may need developers learning new syntax and concepts, which might be difficult for those already familiar with traditional CSS.

2. speed Overhead: Some CSS-in-JS solutions may incur a little speed hit as a result of additional JavaScript processing required to apply styles dynamically.

3. Bundle Size Increase: CSS-in-JS libraries frequently include extra runtime code in the bundle, potentially raising the overall bundle size.

## TailwindCSS
TailwindCSS is another popular option to include CSS in your React project.

It is a utility-first CSS framework for rapidly building custom user interfaces. Here you can easily build modern websites without ever leaving your HTML.

Since TailwindCSS provides utility-first CSS classes, you won’t be working with CSS directly but instead interacting with the predefined Tailwind classes. To reduce bundle sizes, it purges unused classes so you only ship the CSS you need.

For example, you can use “m-2.5” to add a margin of 10px across the top, bottom, right, and left. In the same way, you can use “p-2.5” to add padding of 10px to every direction.

```javascript
function App() {
  return (
    <div className="m-2.5">
      <h1>Hello</h1>
    </div>
  );
}
export default App;
```
**Pros**
1. Responsive Design: Tailwind CSS includes responsive design utilities, making it easy to build responsive layouts that adapt to various screen sizes without the need for writing custom media queries.

2. Small Bundle Size: Tailwind CSS is designed to be highly optimized, and by using only the utility classes needed.

3. Community and Ecosystem: Tailwind CSS has a large and active community, which means extensive documentation, tutorials, and community-built plugins, making it easier to find support and resources.

**Cons:**

1. Learning Curve: Tailwind CSS introduces a unique set of utility classes, which can have a steep learning curve for developers accustomed to traditional CSS frameworks.

2. CSS Bloat: In larger projects, using many utility classes may lead to a significant increase in the size of the generated CSS, which can impact page load times.

3. Limited Creativity: Relying heavily on utility classes might restrict the creativity and customization of styles, leading to a somewhat uniform design across projects.

## Conclusion
In this article we looked at a few alternative approaches to writing styles in a React application. And it's not as though one is superior to the others; the method you choose is determined by the circumstances. Hopefully, you now have a decent understanding of them and are aware that you have a plethora of tools in your React styling armory.