React Components
- React
- JavaScript
The building block of a React app: a function that returns markup describing a piece of the UI, which you compose together to build whole screens.
What you'll understand
- What a React component is
- Why UIs are built by composing components
- The rules that make a function a valid component
Explanation
A React component is a reusable piece of user interface. In modern React it is simply a JavaScript function that returns markup describing what should appear on screen. A component can be as small as a button or as large as a whole page, and you build an application by combining many of them.
Components exist so you can break a complex interface into small, independent, reusable parts. Each component manages one piece of the UI, and you compose them, nesting components inside other components, to assemble a full screen (see Related Topics). This keeps each part simple to understand and lets you reuse the same component wherever you need it.
Two rules make a function a valid component. Its name must start with a capital letter, which is how React tells your components apart from ordinary HTML tags. And it must return renderable markup, written in JSX (see Related Topics). React then calls your function to render it, and calls it again to re-render whenever the data it depends on changes.
Examples
This is a minimal component: a capitalised function that returns markup.
function Welcome() {
return <h1>Welcome to Padlor</h1>;
}You use a component by writing it like a tag, and you can reuse it freely:
function App() {
return (
<main>
<Welcome />
<Welcome />
</main>
);
}Common mistakes
- Naming a component in lowercase, so React treats it as an HTML tag.
- Returning nothing, or forgetting that a component must return markup.
- Building one giant component instead of composing several small ones.
- Defining a component inside another component, so it is recreated on every render.
Best practices
- Give components clear, capitalised names.
- Keep each component focused on one piece of the UI.
- Compose small components rather than writing one large one (see Related Topics).
- Define components at the top level of a module, not inside other components.
Further reading
- React, Your first component — https://react.dev/learn/your-first-component
- React, Importing and exporting components — https://react.dev/learn/importing-and-exporting-components