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.
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
srcassets and use the URL Vite returns. - Reference
publicfiles from the site root, without thepublic/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
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.
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.
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.
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.svgas/brand-mark.svg.
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.
A module import provides a class map whose generated names are local to that stylesheet.
- Name the stylesheet with the
.module.csssuffix. - Use the imported property, such as
styles.button.
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.
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.
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.
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
- For component ownership and reusable UI, see component boundaries and project structure.
- Check accessible React interfaces for image text alternatives, semantics, and contrast.
- Production builds and deployment basics covers static asset output and release checks.
- Review the Vite development workflow for the dev server and build loop.
- If you are moving beyond browser CSS, React Native fundamentals explain its different styling model.
- Read Vite’s guides to assets and CSS modules, plus MDN’s image element reference for alt text behavior.
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.
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.
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.