Components and JSX
Write your first component
Create a capitalized JavaScript function that returns one piece of the interface.
A component is a JavaScript function that returns a piece of the interface.
function Greeting() {
return <h1>Hello</h1>
}
Use it from another component:
export default function App() {
return (
<main>
<Greeting />
</main>
)
}
The capital letter matters. Lowercase JSX names such as <main> and <h1> mean built-in browser elements. A capitalized name such as <Greeting> refers to your JavaScript function.
React calls Greeting() while rendering. The returned JSX becomes part of the next interface snapshot.
You can return multiple elements if you wrap them in a Fragment or a single parent element. A component must return one root node from its function body.
Export the component when another file needs it. export default function Greeting() in its own file keeps App.jsx focused on layout while Greeting.jsx owns the heading markup.
Declare component functions at the top level of the module. Defining Greeting inside App creates a new component type on every render and can reset state below it.
A component should represent a meaningful UI responsibility. Do not wrap every div in a new function. Extract a component when the piece repeats, owns behavior, or becomes clearer with a name.
Save the file and check the browser. You should see Hello inside <main>. Change the text inside Greeting and save again. Vite hot-reloads the module and the heading updates without a full page refresh.
The file name can be Greeting.jsx or Greeting.tsx depending on your project. The component name inside the file should match how you think about the UI, not the DOM tag it renders.
Render two <Greeting /> instances. Confirm React calls the same component function for two different positions in the tree. Each instance is a separate position with its own future state, even when the function body is identical.
Lesson completed