Day 2: Components & Props
Day 2: Components & Props
Welcome back! In Day 1, we set up our environment and wrote some JSX. Today, we learn the extensive power of React: Components.
What is a Component?
A component is a self-contained, reusable piece of UI. Think of them like LEGO bricks. You can have a Button, Navbar, Footer, or UserCard component. You build these small bricks and combine them to build a HomePage or Dashboard.
In modern React, a component is simply a JavaScript Function that returns JSX.
Creating Your First Component
Let’s create a new component. Create a file named Welcome.jsx in your src folder (or just define it in App.jsx for now).
// Welcome.jsx
function Welcome() {
return <h2>Welcome to my App!</h2>;
}
export default Welcome;
Now, we can use this component inside our main App component.
// App.jsx
import Welcome from './Welcome';
function App() {
return (
<div>
<h1>My Application</h1>
{/* We use the component like an HTML tag */}
<Welcome />
<Welcome />
<Welcome />
</div>
);
}
Notice we used <Welcome /> three times. This will render the “Welcome to my App!” message three times. This is reusability.
Props: Passing Data to Components
Right now, our Welcome component is static. It always says the same thing. What if we want to greet different users?
We use Props (short for properties). Props are like function arguments.
Let’s update Welcome to accept a name prop.
function Welcome(props) {
return <h2>Hello, {props.name}!</h2>;
}
Now, we can pass different names when we use the component:
function App() {
return (
<div>
<Welcome name="Alice" />
<Welcome name="Bob" />
<Welcome name="Charlie" />
</div>
);
}
Destructuring Props
It is common convention to destructure props directly in the function signature for cleaner code:
// Instead of props.name
function Welcome({ name }) {
return <h2>Hello, {name}!</h2>;
}
Children Prop
There is a special prop called children. It represents whatever content you put between the opening and closing tags of your component.
function Card({ children }) {
return (
<div className="card-styles">
{children}
</div>
);
}
// Usage
<Card>
<h3>Card Title</h3>
<p>This is the content inside the card.</p>
</Card>
Here, the h3 and p tags are passed as children to the Card component. This is very useful for container components.
Rules of Components
- Capitalize Component Names: React treats components starting with lowercase letters as DOM tags (like
<div>). Always name your componentsMyComponent, notmyComponent. - Return a Single Root Element: You cannot return multiple sibling elements without wrapping them.
// ❌ Error return ( <h1>Title</h1> <p>Text</p> ); // ✅ Correct: Wrap in div or Fragment (<>) return ( <> <h1>Title</h1> <p>Text</p> </> );
Homework for Day 2:
- Create a
UserProfilecomponent that takesusername,age, andisOnlineas props. - Display the user’s info.
- Use the component multiple times with different data in your
App.
Tomorrow, we will make our apps come alive with State!