Define and export function components
Define a reusable piece of UI
A function component is a JavaScript function that React uses to describe part of an interface. Give it a capitalized name and return a renderable value, commonly JSX. A function declaration alone does not display anything. React must encounter an element referring to that component in the tree. Start with the client app from Chapter 3 and replace src/App.jsx with the example below. The visible results in this chapter are predictions, not observed browser tests.
function OpeningHours() { return <p>Open 9 am to 5 pm</p>;}
export default function App() { return ( <main> <h1>Community workshop</h1> <OpeningHours /> </main> );}Expected page: the heading Community workshop followed by Open 9 am to 5 pm. App is the component that the entry module mounts. OpeningHours is a separate component used inside App. The tag <OpeningHours /> describes a component element; it is not an HTML tag named OpeningHours. React evaluates the component to obtain the paragraph. Changing the returned text changes the description for each place it is used.
Separate components into modules
As a component becomes useful in several files, export it. JavaScript permits one default export per module and multiple named exports. Default imports may choose a local name; named imports use the exported name unless explicitly renamed. Keep the two files below in the same src directory. Together they are one example, not two independent apps.
export default function WorkshopNotice() { return <p>Bring your own notebook.</p>;}
export function Location() { return <p>Room 12</p>;}import WorkshopNotice, { Location } from './WorkshopNotice.jsx';
export default function App() { return ( <main> <h1>Today's workshop</h1> <WorkshopNotice /> <Location /> </main> );}Expected page: Today's workshop, Bring your own notebook., and Room 12 in that order. The first import has no braces because it imports the default export. Location uses braces because it is a named export. The relative path points to a file in the same directory. The existing main.jsx still imports App as its default export. File names are project conventions; React does not require every component to occupy its own file.
Avoid naming and import mistakes
If you write <openingHours />, JSX treats the lowercase name as a host element name rather than resolving the function. If you use import { WorkshopNotice } with the module above, the module has no named export with that name. Match the export style and exact path, including case on case-sensitive file systems. Do not write OpeningHours() to render a child: use its JSX element so React manages the component boundary.
Practice
Create a separate ContactDetails module with a named Room component and a default ContactDetails component. Import both into App and predict the display. The next lesson builds a tree from reusable components.