Beginner4 min readUpdated
React / 21
Splitting files: default and named exports
TL;DR
One component per file, data in its own module, and the two ways files share code. Plus when a file must be .jsx instead of .js.
A common layout
src/
components/one component per file
Header.jsxexport default Header
Body.jsxexport default Body
RestaurantCard.jsxexport default RestaurantCard
utils/not components
constants.jsexport const LOGO_URL …
mockData.jsexport const restaurants …
App.jsximports Header, Body
main.jsxcreateRoot(…).render(<App />)
src/holds all your code. It's a convention, not a rule, but every tool and teammate expects it.components/gets one component per file, named in PascalCase to match the component:Header.jsx.utils/(ordata/,lib/) holds things that aren't components: constants, mock data, helpers. Those files use camelCase:constants.js.- Keep hard-coded URLs and mock data out of component files. When the logo URL changes, you edit one line in one place.
Default export: the main thing in a file
import { LOGO_URL } from "../utils/constants";
function Header() {
return (
<header className="header">
<img className="logo" src={LOGO_URL} alt="Tasty Bites" />
</header>
);
}
export default Header;import Header from "./components/Header";No braces, and the importing file picks the name. A file can have one default export at most. You can also write it in one go: export default function Header() { … }.
Named exports: many things from one file
export const LOGO_URL = "https://example.com/logo.png";
export const IMG_CDN_URL = "https://example.com/images/";import { IMG_CDN_URL } from "../utils/constants";With braces, and the name must match the export. Rename on the way in with as: import { LOGO_URL as logo } from "../utils/constants".
Both in one file
export const MIN_TOP_RATING = 4.2;
export default function RestaurantCard({ name }) {
return <h3>{name}</h3>;
}import RestaurantCard, { MIN_TOP_RATING } from "./components/RestaurantCard";| Default | Named | |
|---|---|---|
| Per file | at most one | as many as you like |
| Export | export default Header; | export const LOGO_URL = …; |
| Import | import Header from "./Header" | import { LOGO_URL } from "./constants" |
| Name when importing | your choice | must match (or use as) |
.js or .jsx?
- A file with JSX should be
.jsx(or.tsxwith TypeScript). In a Vite project this is required by default: JSX inside a.jsfile fails to compile unless you change the config. - A file without JSX (
constants.js,mockData.js) stays.js. - With a bundler you can leave the extension off in imports:
"./components/Header"findsHeader.jsx. Browsers loading modules directly (no bundler) need the full path.
Gotchas
Recall
Can you answer these?
0/4
Answer out loud (or in your head) before you tap. That's what makes it stick.
Saved on this device only. No login.
