How to Pass and Use Props in React
React props (properties) are the primary mechanism for passing data from parent to child components, enabling the creation of dynamic and reusable user interfaces. This article provides a straightforward guide on how to implement React props, covering how to pass data, receive it in a child component, and use modern techniques like destructuring to write cleaner code.
Understanding React Props
Props are read-only objects that store attributes passed to a component. They mimic standard HTML attributes and allow data to flow unidirectionally (downwards) from parent components to child components. Because props are immutable, a child component must never modify the props it receives.
Step 1: Passing Props from a Parent Component
To pass data to a child component, define custom attributes on the
child component’s JSX tag inside the parent component. You can pass
strings, numbers, arrays, objects, functions, or booleans. When passing
non-string values, wrap them in curly braces {}.
// ParentComponent.jsx
import ChildComponent from './ChildComponent';
function ParentComponent() {
return (
<div>
<ChildComponent title="Welcome to React" score={100} isLoggedIn={true} />
</div>
);
}
export default ParentComponent;Step 2: Receiving Props in a Child Component
The child component receives these attributes as a single object,
typically named props, passed as the first argument to the
functional component. You can access the individual values using dot
notation.
// ChildComponent.jsx
function ChildComponent(props) {
return (
<div>
<h1>{props.title}</h1>
<p>Your score is: {props.score}</p>
{props.isLoggedIn ? <p>Status: Active</p> : <p>Status: Offline</p>}
</div>
);
}
export default ChildComponent;Step 3: Destructuring Props for Cleaner Code
Instead of repeating props. throughout your component,
you can use ES6 destructuring. This extracts the specific properties
directly within the function’s parameter list, making the code much
easier to read.
// ChildComponent.jsx (Using Destructuring)
function ChildComponent({ title, score, isLoggedIn }) {
return (
<div>
<h1>{title}</h1>
<p>Your score is: {score}</p>
{isLoggedIn ? <p>Status: Active</p> : <p>Status: Offline</p>}
</div>
);
}
export default ChildComponent;Setting Default Values for Props
If a parent component does not pass a specific prop, you can define default values to prevent rendering errors. The modern standard in React is to use JavaScript’s default parameters directly in the destructured arguments.
function ChildComponent({ title = "Default Title", score = 0 }) {
return (
<div>
<h1>{title}</h1>
<p>Score: {score}</p>
</div>
);
}