React / 13
Function components
A component is a JavaScript function that returns JSX. Give it a capital letter, use it like a tag, and you've built your own HTML element.
A component is a function
function MenuCard() {
return (
<article className="card">
<h3>Masala Dosa</h3>
<p>₹80</p>
</article>
);
}That's all a function component is: a plain JavaScript function that returns JSX. Return null when it should show nothing.
function MenuCard() { return <h3>Masala Dosa</h3>; }
- 1 · a plain JavaScript function, named with a Capital letter
- 2 · returns JSX (or
nullfor nothing) - 3 · used like a tag:
<MenuCard />
capital letter → your component
<MenuCard />jsx(MenuCard): React calls your function
lowercase → an html tag
<menuCard />jsx("menuCard"): an unknown tag. Your function never runs.
Using it
<MenuCard />
<MenuCard></MenuCard> {/* same thing; the short form is preferred */}When React meets <MenuCard />, it calls your function, takes the JSX it returns, and puts that on the screen. You never call it yourself.
Three ways to write the same component
function Logo() {
return <h1>Tasty Bites</h1>;
}const Logo = () => {
return <h1>Tasty Bites</h1>;
};const Logo = () => <h1>Tasty Bites</h1>;All three are identical to React. Function declarations are common for components (React's own docs use them); arrow functions are just as fine. Pick one style per project.
Why the capital letter matters
The compiler decides from the first letter:
| You write | Compiles to | Means |
|---|---|---|
<menuCard /> | jsx("menuCard", {}) | A string: an HTML tag called menuCard |
<MenuCard /> | jsx(MenuCard, {}) | The variable MenuCard: your function |
So a lowercase component never runs. React creates an unknown <menucard> tag in the page and warns: "The tag <menuCard> is unrecognized in this browser. If you meant to render a React component, start its name with an uppercase letter."
One component per file
export default function MenuCard() {
return <h3>Masala Dosa</h3>;
}import MenuCard from "./MenuCard.jsx";
export default function App() {
return (
<main>
<MenuCard />
<MenuCard />
</main>
);
}Put each component in its own file, named after it, and export it. Small files are easier to find, test and change, and Fast Refresh works best when a file exports only components.
Component vs element
Two words that people mix up:
- Component: the function.
MenuCard. - Element: what
<MenuCard />produces, a plain object ({ type: MenuCard, props: {} }) that says "renderMenuCardhere".
A component is the recipe; an element is one order slip for it. Rendering <MenuCard /> twice makes two elements from one component.
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.
