Named Exports

export default exports one thing, the file's main one. A file can also export several things, each under its own name. These are named exports, and you write just export in front of each function:

// Badges.jsx
export function NewBadge() {
    return <span className="badge">New</span>;
}

export function SoldOutBadge() {
    return <span className="badge">Sold out</span>;
}

An import of named exports lists their names in curly braces, separated by commas:

import { NewBadge, SoldOutBadge } from "./Badges.jsx";

The curly braces are the difference to watch for:

  • A default export is imported without braces, and you choose its name: import Header from "./Header.jsx";
  • Named exports are imported with braces, under their exact names: import { NewBadge } from "./Badges.jsx";. You import just the ones you need.

That's why main.jsx has import { createRoot } from "react-dom/client";: createRoot is a named export of the package. A file can have both, one default export and any number of named ones. And it can export any value, not just components, for example export const festival = "Summer Sounds";.

Which one to use? Most React projects give each component a file of its own with a default export, as you did with Header. Named exports suit a file with several small things that belong together, such as a few badges or tickets, or data that several components use.

Mixing them up is a common mistake. An import without braces needs a default export, and one with braces needs a named export of that name. When they don't match, the import gets undefined, the page is empty, and the console says Element type is invalid: … but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

Instructions

Tickets.jsx has a component FridayTicket, exported by name. Import it in App.jsx and put <FridayTicket /> into the div with the class tickets, in place of the comment.

In Tickets.jsx, write two more components like it, each exported by name: SaturdayTicket (Saturday, €45) and WeekendTicket (Weekend, €80). Import all three with one import and show them after FridayTicket.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

Back

3/6

Next