Chapter 4 of 4
Your First Component
Write, render and edit a real React component in the browser.
A component is a JavaScript function whose name starts with a capital letter and which returns something React can render. That is the entire rule.
function Welcome() {
return <h1>Hello, React!</h1>;
}Why the capital letter matters
JSX uses the case of the tag name to decide what you meant. A lowercase tag such as <div> is treated as a built-in HTML element. A capitalised tag such as <Welcome> is treated as a reference to a component variable in scope.
function welcome() {
return <h1>Hi</h1>;
}
// React renders a literal <welcome> HTML tag, not your function
const wrong = <welcome />;
// This is what you meant
const right = <Welcome />;Rendering a component
Components only appear on screen once something renders them. At the top of the tree, createRoot connects React to a DOM node; below that, components render each other.
import { createRoot } from "react-dom/client";
function Welcome() {
return <h1>Hello, React!</h1>;
}
createRoot(document.getElementById("root")).render(<Welcome />);Write your first component
Make the Greeting component return an h1 that says exactly: Hello, React!
What you have learned
- React is a library for describing user interfaces rather than instructing the DOM.
- JSX produces plain objects called elements; React diffs them and updates the DOM minimally.
- Vite or Next.js will set up a working project for you in one command.
- A component is a capitalised function that returns renderable output.