React Basics: Components and Props
After completing this topic
You will be able to create components in React, pass data using Props, and combine multiple components to construct a user interface.
Why React?
You can create web pages using plain HTML and JavaScript. However, problems arise as the page becomes more complex:
<!-- What if you need to repeat the same card structure 10 times? -->
<div class="card">
<h3>First item</h3>
<p>Description...</p>
</div>
<div class="card">
<h3>Second item</h3>
<p>Description...</p>
</div>
<!-- ... 8 more times -->Copying and pasting HTML means you have to modify 10 places whenever you want to change the design. React solves this problem with components β reusable UI building blocks.
What is a Component?
A component is a function that returns UI.
function Card() {
return (
<div className="card">
<h3>Title</h3>
<p>Description</p>
</div>
);
}This is a component. The HTML-like syntax is called JSX. It allows you to write markup within JavaScript. Since browsers cannot directly understand JSX, it is transformed into plain JavaScript during the build process.
Component names must start with a capital letter. If they start with a lowercase letter, React will recognize them as HTML tags.
Using Components
Use the created component as a tag within other components:
function App() {
return (
<div>
<Card />
<Card />
<Card />
</div>
);
}Writing <Card /> three times renders the same UI three times. If you want to change the design, you only need to modify the Card function.
Props: Passing Data to Components
So far, our Card component always displays the same content. To display different data in each card, we use Props (short for Properties).
function Card(props) {
return (
<div className="card">
<h3>{props.title}</h3>
<p>{props.description}</p>
</div>
);
}
function App() {
return (
<div>
<Card title="HTML" description="The backbone of the web" />
<Card title="CSS" description="The clothing of the web" />
<Card title="JS" description="The brain of the web" />
</div>
);
}{props.title} β in JSX, curly braces {} mean "put the JavaScript value here." Props are data passed unidirectionally from a parent component to a child component.
Receiving Props with Destructuring
Writing props.title and props.description every time can be cumbersome. In practice, we use destructuring:
function Card({ title, description }) {
return (
<div className="card">
<h3>{title}</h3>
<p>{description}</p>
</div>
);
}We extract the props directly from the function parameter using { title, description }. The meaning is the same, but the code becomes cleaner.
Various Types of Props
Props can pass not only strings, but also numbers, arrays, objects, and functions:
function UserProfile({ name, age, hobbies, onFollow }) {
return (
<div>
<h2>{name} ({age} years old)</h2>
<ul>
{hobbies.map((hobby, i) => (
<li key={i}>{hobby}</li>
))}
</ul>
<button onClick={onFollow}>Follow</button>
</div>
);
}
// Usage
<UserProfile
name="Chul-soo"
age={25}
hobbies={["Coding", "Gaming", "Reading"]}
onFollow={() => alert("Followed!")}
/>Strings are enclosed in quotation marks, and other values are enclosed in curly braces {}. The pattern of using map() to iterate over an array and render a list is very common in React.
children: A Special Prop
Any content placed between a component's tags is passed as a special prop called children:
function Container({ children }) {
return (
<div className="container">
{children}
</div>
);
}
// Usage
<Container>
<h1>Title</h1>
<p>Everything inside here is children</p>
</Container>Using children, you can create layout components β a pattern where the outer frame is fixed, and only the inner content changes.
Component Separation Criteria
When should you separate a component?
- Repeated UI fragments β Extract into a component
- Independent functionality β Separate into a component
- When the screen becomes too long β Separate into sections
App
βββ Header
βββ Main
β βββ SearchBar
β βββ CardList
β βββ Card
β βββ Card
β βββ Card
βββ FooterThis tree structure is the core idea of React.
Setting Default Values for Props
You can set default values to handle cases where Props are not passed:
function Badge({ label = "NEW", color = "#3498db" }) {
return (
<span style={{
backgroundColor: color,
color: "white",
padding: "4px 8px",
borderRadius: "4px",
fontSize: "12px"
}}>
{label}
</span>
);
}
// Using default values
<Badge /> // "NEW" + blue
<Badge label="HOT" /> // "HOT" + blue
<Badge label="SALE" color="red" /> // "SALE" + redBy setting default values, the component using the component does not have to pass all Props. You can optionally specify only the ones you need.
Things to Keep in Mind in JSX
JSX is similar to HTML, but there are some important differences:
// 1. Use className instead of class
<div className="container"> // β
<div class="container"> // β class is a JavaScript reserved word
// 2. Use htmlFor instead of for
<label htmlFor="email">Email</label> // β
// 3. You must wrap it in a single root element
function Wrong() {
return (
<h1>Title</h1> // β Two root elements
<p>Content</p>
);
}
function Right() {
return (
<> // β
Wrap with a Fragment
<h1>Title</h1>
<p>Content</p>
</>
);
}
// 4. Styles are objects
<div style={{ backgroundColor: "red", fontSize: "16px" }}>
// camelCase + string values
</div><> and </> are called Fragments. They allow you to group multiple elements without unnecessary <div> wrappers.
Conditional Rendering
You can display different UIs depending on the value of the Props:
function StatusBadge({ isOnline }) {
return (
<span>
{isOnline ? "π’ Online" : "βͺ Offline"}
</span>
);
}
function Notification({ count }) {
return (
<div>
Notifications
{count > 0 && <span className="badge">{count}</span>}
</div>
);
}The && operator renders the right side only if the left side is true. The ternary operator is used when you want to show both true and false. These two patterns handle most of the conditional rendering in React.
Key Takeaways
| Concept | Description |
|---|---|
| Component | A function that returns UI (starts with a capital letter) |
| JSX | A syntax for writing markup within JavaScript |
| Props | Unidirectional data passing from parent to child |
| children | A special prop that passes the content between tags |
| Destructuring | Cleanly receive Props using ({ title }) |
| Default Values | Handle cases where Props are not passed using ({ label = "NEW" }) |
| Fragment | <>...</> Remove unnecessary wrapper div |
The most important thing to learn when first learning React is to understand "what data flows where." Props always flow from top to bottom. If the child wants to change the parent's data, the parent provides a function as a prop that the child can call to update its state β this connects to State, which we will learn next.
β Apply to bio: DevBench β React Intro