Props in React
Imagine you have a reusable `Button` component. You want it to say "Click Me" in one place, "Submit" in another, and "Cancel" somewhere else. How does the component know what text to show? This is where **props** come in.
Props (short for "properties") are read-only inputs passed to React components. They are like arguments to a function – they allow you to customize a component when you use it.
Props are how data flows from a parent component to a child component. They are read-only – a child component can never modify its own props.
How to Pass Props
Props are passed to components just like HTML attributes.
<Greeting name="Alice" age={25} isLoggedIn={true} />Here we're passing three props: `name` (string), `age` (number), and `isLoggedIn` (boolean).
How to Receive Props
In Functional Components: Props are received as the first argument.
function Greeting(props) { return <h1>Hello, {props.name}! You are {props.age}.</h1>;}In Class Components: Props are accessed via `this.props`.
class Greeting extends React.Component { render() { return <h1>Hello, {this.props.name}!</h1>; }}Destructuring Props
A common pattern is to destructure props directly in the function parameter for cleaner code.
function Greeting({ name, age }) { return <h1>Hello, {name}! You are {age}.</h1>;}Props are Read-Only
This is a fundamental rule of React: a component must never modify its own props. Props are like immutable ingredients given to a recipe – you can use them to create the dish, but you can't change the ingredients themselves.
Wrong: `props.name = "Bob";` (never do this!)
If you need to modify data, that data should be stored in the component's state (which we'll learn about later).
Special Prop: children
Every component automatically receives a `children` prop. It contains whatever is placed between the opening and closing tags of the component.
function Wrapper({ children }) { return <div className="wrapper">{children}</div>;}
function App() { return ( <Wrapper> <h1>This is inside the wrapper!</h1> <p>So is this paragraph.</p> </Wrapper> );}The `Wrapper` component will render its children inside the div.
Two Minute Drill
- Props (properties) are read-only inputs passed to React components.
- They allow parent components to pass data down to child components.
- In functional components, props are the first argument; in class components, they're accessed via `this.props`.
- Props are immutable – a component cannot change its own props.
- The `children` prop is a special prop that contains content between opening and closing tags.
- Destructuring props makes code cleaner and more readable.
Need more clarification?
Drop us an email at career@quipoinfotech.com
