π Day 2: Understanding Props & Children in React β Building a User Profile Card
π₯ Introduction
Welcome to Day 2 of the 100 Days of React Challenge! π Today, we will learn about Props & Children in React by building a User Profile Card.
Props (short for properties) allow us to pass data from a parent component to a child component, making our components dynamic and reusable.
π― Problem Statement (Step by Step)
Step 1: Understanding the Problem
- We need to create a UserProfile component that accepts
name
andimage
as props. - It should display a profile picture, name, and a description.
- The parent component (
App.js
) will pass different data to theUserProfile
component.
π Solution β Writing the Code
1οΈβ£ Create the UserProfile
Component
Inside the src/components/
folder, create a new file UserProfile.jsx
:
const UserProfile = ({ name, image, children }) => {
return (
<div style={styles.card}>
<img src={image} alt={name} style={styles.image} />
<h2>{name}</h2>
<p>{children}</p>
</div>
);
};
const styles = {
card: {
border: "1px solid #ddd",
padding: "20px",
borderRadius: "10px",
width: "250px",
textAlign: "center",
boxShadow: "2px 2px 10px rgba(0, 0, 0, 0.1)",
},
image: {
width: "100px",
height: "100px",
borderRadius: "50%",
},
};export default UserProfile;
π Explanation:
- The
UserProfile
component receivesname
andimage
as props. - We use
{children}
to allow passing extra content (like a bio). - Inline styles are used for quick styling.
2οΈβ£ Use the Component in App.js
Now, update App.js
to import and use the UserProfile
component:
import React from "react";
import UserProfile from "./components/UserProfile";
const App = () => {
return (
<div>
<h1>React 100 Days Challenge</h1> <UserProfile name="Rahul" image="https://via.placeholder.com/100">
Frontend Developer | Loves React π
</UserProfile> <UserProfile name="Emily" image="https://via.placeholder.com/100">
UI/UX Designer | Passionate about user experience β¨
</UserProfile>
</div>
);
};export default App;
Expected Output:
π Displays two profile cards with images, names, and descriptions.
π― Concepts We Learned Today
π Props (name
, image
) β Used to pass data to child components.
π Children Prop β Used to pass extra content inside a component.
π Reusable Components β We created a generic UserProfile
component.
π― Bonus: Interactive Quiz!
Try answering this MCQ question π
Which of the following statements about React props is correct?
A) Props can only pass text values.
B) Props cannot be changed inside a component.
C) Props are the same as state.
D) A component cannot have multiple props.
π‘ Drop your answers in the comments below! π
π Great job! Today, we learned about props and children in React! π
Tomorrow, weβll explore handling click events in React. Stay tuned!
π₯ Did you enjoy this? Share this with your developer friends!
π¬ Got questions? Drop a comment, and letβs discuss.