Styling React Components and Importing Assets

Compare plain CSS with CSS modules, then learn how Vite handles imported files and public assets in React projects, with practical code examples.

published: reading time: 7 min read author: Geek Workbench
Quick Summary

Choose global CSS for rules the whole app shares and CSS modules when selectors belong to one component. Vite tracks imported files from `src` and rewrites their URLs for production, while files in `public` keep fixed root paths. Examples show both choices, how nested routes can expose path mistakes, and why public assets must never contain secrets.

Styling React Components and Importing Assets

Introduction

React components can share styles globally or scope class names to one file. Images also need paths that work in both development and production. Vite has simple conventions for both.

This post compares global CSS and CSS modules, then explains when to import assets from src or serve them from public.

Plain CSS or CSS modules?

Keep resets, theme tokens, and site-wide rules in plain CSS. Use a CSS module when selectors belong to a single component; Vite scopes the imported class names for you.

/* TaskCard.module.css */
.card {
  border: 1px solid #777;
  padding: 1rem;
}

.title {
  margin: 0 0 0.5rem;
}
import styles from "./TaskCard.module.css";

function TaskCard({ title }: { title: string }) {
  return (
    <article className={styles.card}>
      <h2 className={styles.title}>{title}</h2>
    </article>
  );
}

Import local assets in Vite

An image under src can be imported like a module. Vite includes it in the build and returns a URL for the image:

import logoUrl from "./assets/logo.svg";

function Brand() {
  return <img src={logoUrl} alt="Acme home" />;
}

Use imports for assets referenced by application code. Vite updates the generated filename and URL together in the build.

Use the public directory for files that need a fixed name or are referenced by a URL rather than a source import, such as robots.txt or a favicon. For public/brand-mark.svg, write /brand-mark.svg in markup; do not include the public folder in the URL. Vite copies public files to the output root as-is.

flowchart LR
    A[React source] --> B{Asset location}
    B -->|src import| C[Vite processes and emits URL]
    B -->|public path| D[Copied with original name]
    C --> E[Production build]
    D --> E

Production Failure Scenarios

A common mistake is writing src="public/logo.svg" for a file in public. The browser requests that literal path; use /logo.svg. For files in src, import the file instead of guessing a /src/... URL. If an image fails only on nested routes, check the network panel: relative URLs resolve from the current page path. Another production failure is a case mismatch such as Logo.svg versus logo.svg; local development on a case-insensitive filesystem can hide it. Match the exact filename and verify the built asset request.

Security and Compliance Notes

Files in public are served to every visitor, so never place private keys or confidential files there. Give meaningful images useful alt text and use alt="" for decorative images. Styling has no special compliance requirement by itself; check contrast and do not rely on color alone to communicate status.

When to Use / When NOT to Use

Use global CSS for resets and site-wide tokens; use CSS modules when selectors belong to one component. Import files from src when the build should track and fingerprint them. Use public for fixed-name files that need a stable root URL. Avoid public for secrets or imported assets whose generated URL should follow the build.

Trade-Off Table

Choice Benefit Trade-off
Global CSS Shared rules stay in one place Selectors can affect unrelated components
CSS modules Local selector scope Shared styles need deliberate reuse
Imported asset Build tracks and fingerprints the file Callers use the generated URL
public asset Stable filename and root URL No import-time missing-file check

Observability Checklist

  • Check build output for unresolved asset imports.
  • Inspect 404s with the asset path and page route.
  • Keep private file contents out of logs and bug reports.

Common Pitfalls / Anti-Patterns

Avoid writing public/ into the browser URL, guessing /src/... paths, or relying on relative URLs from nested routes. Confirm the exact filename capitalization and use image alt text intentionally.

Quick Recap Checklist

  • Use plain CSS for shared global rules and CSS modules for component-owned selectors.
  • Import src assets and use the URL Vite returns.
  • Reference public files from the site root, without the public/ prefix.
  • Keep secrets out of public assets and add appropriate image alt text.
  • Check network requests when paths fail in production or nested routes.

Interview Questions

1. When would you choose CSS modules over plain CSS?

Choose CSS modules for selectors owned by one component, especially when generic names might collide. Plain CSS remains useful for resets and shared site-wide rules.

2. What is the difference between importing an asset and using the public directory?

An imported asset becomes part of Vite's build graph and the import provides its URL. A public file keeps its name and is referenced by a root path such as /logo.svg.

3. Why can a relative asset path break on a nested route?

A relative URL resolves from the current page URL, which may include nested path segments. Use an imported asset URL or the correct root path for public files.

4. When should an image live in public?

Use public when a stable filename or direct root URL is useful.

  • Vite copies the file to the output root as-is.
  • Reference public/brand-mark.svg as /brand-mark.svg.
5. What does importing an asset from src let Vite do?

The import adds the file to Vite's build graph.

  • Vite can emit and fingerprint it for the production build.
  • Use the URL returned by the import in the component.
6. How do CSS modules scope a class?

A module import provides a class map whose generated names are local to that stylesheet.

  • Name the stylesheet with the .module.css suffix.
  • Use the imported property, such as styles.button.
7. Why should private files stay out of public?

Files in that directory are copied into the publicly served build.

  • Do not place credentials or confidential documents there.
  • Keep private data on a protected server.
8. How should decorative images be described?

Use an empty alt attribute when the image adds no information.

  • Provide useful alternative text for informative images.
  • Do not repeat nearby text without adding meaning.
9. What can an image 404 on a nested page indicate?

A relative URL may be resolving from that nested route.

  • Inspect the requested URL in the network panel.
  • Use an imported URL or a correct root-relative public path.
10. When is global CSS a better fit than a CSS module?

Use global styles for shared rules such as resets, themes, and site-wide utilities.

  • Scope component-specific selectors with modules.
  • Keep the selector's ownership clear to avoid collisions.

Further Reading

Conclusion

Use global CSS for shared rules and modules for component styles. Import files from src; use root URLs for fixed-name files in public. This keeps asset paths reliable across environments.

Category

Related Posts

Vite Development Workflow for React and TypeScript

Learn a practical Vite workflow for React and TypeScript: create a project, use hot reload, build, preview, and protect environment values.

#vite #react #typescript

Accessible React UI: Semantics, Labels, and Keyboard Use

Build React interfaces with semantic controls, connected labels, visible keyboard focus, and status announcements through practical TypeScript examples.

#react #typescript #accessibility

DOM, HTML, and CSS for React Interface Basics

Understand how semantic HTML, the browser DOM, CSS layout, and React updates fit together when building accessible, predictable interfaces.

#react #html #css