Back to Blog

CSS-in-JS: Modern Approaches

Anonymous
March 31, 2024
7 min read

Modern Approaches to CSS-in-JS

CSS-in-JS has evolved significantly over the years. Let's explore modern approaches and their use cases.

Styled Components

Basic Usage

import styled from "styled-components";

const Button = styled.button`
  background: ${(props) => (props.primary ? "blue" : "white")};
  color: ${(props) => (props.primary ? "white" : "blue")};
  padding: 0.5em 1em;
  border: 2px solid blue;
  border-radius: 3px;
`;

Theme Support

const theme = {
  colors: {
    primary: "#007bff",
    secondary: "#6c757d",
  },
};

const ThemedButton = styled.button`
  background: ${({ theme }) => theme.colors.primary};
  color: white;
`;

Emotion

CSS Prop

import { css } from "@emotion/react";

const styles = css`
  background: #f0f0f0;
  padding: 20px;
  border-radius: 8px;
`;

function Component() {
  return <div css={styles}>Content</div>;
}

Styled Components

import styled from "@emotion/styled";

const Card = styled.div`
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  padding: 16px;
  margin: 8px;
`;

Tailwind CSS

Utility-First Approach

function Component() {
  return (
    <div className="flex items-center justify-between p-4 bg-white rounded-lg shadow-md">
      <h1 className="text-2xl font-bold text-gray-800">Title</h1>
      <button className="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600">
        Click me
      </button>
    </div>
  );
}

CSS Modules

Component-Specific Styles

// styles.module.css
.button {
  background: #007bff;
  color: white;
  padding: 8px 16px;
  border-radius: 4px;
}

// Component.tsx
import styles from './styles.module.css';

function Component() {
  return <button className={styles.button}>Click me</button>;
}

Conclusion

Choose your CSS-in-JS solution based on:

  1. Project requirements
  2. Team preferences
  3. Performance needs
  4. Bundle size constraints
  5. Development experience