React Lesson 5: Props — Passing Data to Components

⚛️ React CourseLesson 5 of 15 · 33% complete

Props (properties) let you pass data from a parent component to a child component. They make components flexible and reusable.

Passing and Receiving Props

// Parent passes props like HTML attributes
function App() {
  return (
    <div>
      <Greeting name="Alice" />
      <Greeting name="Bob" />
      <Greeting name="Charlie" />
    </div>
  );
}

// Child receives props as first parameter
function Greeting({ name }) {
  return <h1>Hello, {name}!</h1>;
}

Multiple Props

function UserCard({ name, age, role, isOnline }) {
  return (
    <div className="user-card">
      <h3>{name}</h3>
      <p>Age: {age} | Role: {role}</p>
      <span className={isOnline ? "online" : "offline"}>
        {isOnline ? "Online" : "Offline"}
      </span>
    </div>
  );
}

// Usage:
<UserCard name="Alice" age={30} role="Admin" isOnline={true} />

Props with Functions (onClick etc.)

function Button({ label, onClick, variant = "primary" }) {
  return (
    <button
      className={`btn btn-${variant}`}
      onClick={onClick}
    >
      {label}
    </button>
  );
}

// Usage:
<Button label="Save" onClick={() => console.log("Saved!")} />
<Button label="Delete" onClick={handleDelete} variant="danger" />

children Prop

function Card({ title, children }) {
  return (
    <div className="card">
      <h2>{title}</h2>
      <div className="card-body">
        {children}
      </div>
    </div>
  );
}

// Usage:
<Card title="My Card">
  <p>This paragraph is the children prop!</p>
  <button>Click me</button>
</Card>

🏋️ Practice Task

Build a reusable Alert component that accepts: type (“success”/”error”/”warning”), title, and message props. The type changes the background color. Test with 3 different Alert instances. Add a default type of “info”.

💡 Hint: const colors = {success:”green”,error:”red”,warning:”yellow”,info:”blue”}. Use style={{backgroundColor: colors[type] || colors.info}}

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *