Runnable lesson · press Try it on the examples to edit and run them here.
A React component is a JavaScript function that returns JSX. Let us write one and use it.
Step 1: write the function
function Greeting() {
return <p>Hello, I am a component</p>;
}
function App() {
return <Greeting />;
}
Greeting is the component. App uses it by writing <Greeting /> like an HTML tag.
The rules
- Start the name with a capital letter.
Greeting, notgreeting. - Return JSX (or
nullto show nothing). - Use it as a tag:
<Greeting />, notGreeting(). - Keep it a function you define at the top of the file, not inside another component.
Step 2: make it do more
A component can contain anything a function can: variables, calculations, other components.
function Greeting() {
const hour = new Date().getHours();
const timeOfDay = hour < 12 ? "morning" : hour < 18 ? "afternoon" : "evening";
return <p>Good {timeOfDay}! Welcome to React.</p>;
}
function App() {
return (
<main>
<h1>My first component</h1>
<Greeting />
<Greeting />
</main>
);
}
Two things to notice. First, the code before return is ordinary JavaScript and runs every time the component renders. Second, <Greeting /> is used twice, so we get two paragraphs from one definition. That reuse is the whole point.
Where the component goes in a real project
In a real project, each component usually lives in its own file and App.jsx imports it. You will do that in Importing and Exporting Components. In the playground, everything goes in one file.
Common mistakes
- A lowercase name. React treats
<greeting />as an HTML tag calledgreeting, which does nothing useful. - Returning two siblings.
return <h1>Hi</h1><p>there</p>;is an error. Wrap them in one parent or a Fragment (see Fragments). - Forgetting
return. A component that does not return anything shows nothing and React logs an error. - Putting a statement where an expression is needed. You cannot write an
ifinside JSX braces. Use a ternary or compute a value first.
Key points
- A component is a function with a capitalised name that returns JSX.
- Use it as a tag. Use it as many times as you like.
- Code before
returnis regular JavaScript that runs on each render.
Exercise: A Footer component
Write a Footer component that shows “Made with React” in a <footer> element, and show it under a heading in App. —solution
function Footer() {
return <footer><small>Made with React</small></footer>;
}
function App() {
return (
<div>
<h1>My page</h1>
<Footer />
</div>
);
}