|4. Props in React
Chapter 4React Tutorial~1 min read

Props in React

Props — Components ला Data पाठवणे

Props (Properties) म्हणजे parent component कडून child component ला data पाठवायचा way. Function parameters सारखे आहे — component ला outside data देतात. Props read-only असतात — child त्यात बदल करू शकत नाही.

Marathi Analogy

Props म्हणजे idli maker ला ingredients देण्यासारखे. Idli maker (component) तसाच राहतो, फक्त ingredients (props) बदलतात. एकाच maker ने coconut chutney वाले किंवा sambar वाले idli बनवता येतात!

Props pass करणे आणि receive करणे

jsx
// Child component — props receive करतो
function Greeting({ name, city }) {   // destructuring
  return (
    <div>
      <h2>नमस्कार, {name}!</h2>
      <p>{city} मधून आलात का?</p>
    </div>
  );
}

// Parent component — props pass करतो
export default function App() {
  return (
    <div>
      <Greeting name="Rahul" city="Pune" />
      <Greeting name="Priya" city="Mumbai" />
      <Greeting name="Amit" city="Nagpur" />
    </div>
  );
}

Different Types of Props

String, number, boolean, object, function props

jsx
function UserCard({ name, age, isPremium, skills, onFollow }) {
  return (
    <div className="card">
      <h2>{name}</h2>
      <p>Age: {age}</p>
      {isPremium && <span>⭐ Premium Member</span>}
      <ul>
        {skills.map(skill => <li key={skill}>{skill}</li>)}
      </ul>
      <button onClick={onFollow}>Follow</button>
    </div>
  );
}

// वापरणे
<UserCard
  name="Rahul"
  age={25}                          // number — {} मध्ये
  isPremium={true}                  // boolean — {} मध्ये
  skills={["React", "JS", "CSS"]}  // array — {} मध्ये
  onFollow={() => alert("Followed!")}  // function — {} मध्ये
/>

children Prop — Special Prop

children — wrapper components साठी

jsx
// Card component — wrapper म्हणून वापरतो
function Card({ title, children }) {
  return (
    <div className="border rounded-xl p-4">
      <h3 className="font-bold">{title}</h3>
      <div>{children}</div>  {/* जे आत लिहू ते येथे */}
    </div>
  );
}

// वापरणे — tags च्या आत जे लिहू ते children
function App() {
  return (
    <Card title="माझी Profile">
      <p>नाव: Rahul Patil</p>
      <p>शहर: Pune</p>
      <button>Edit करा</button>
    </Card>
  );
}

Key Points — लक्षात ठेवा

  • Props = parent → child data flow (one-way)
  • function Comp({ prop1, prop2 }) — destructuring
  • Strings: prop="value", बाकी सगळे: prop={value}
  • Props immutable — child त्यात बदल करू शकत नाही
  • children — opening आणि closing tags च्या मधला content
0/12 chapters पूर्ण