How to Pass Props to Component in React: Simple Guide
In React, you pass data to components using
props by adding attributes to the component tag, like <ComponentName propName={value} />. Inside the component, access these values via the props object or by destructuring in the function parameters.Syntax
To pass props, write the component tag with attributes representing each prop. Inside the component, use props.propName or destructure props in the function parameters.
- Component usage:
<ComponentName propName={value} /> - Function component:
function ComponentName(props) {}orfunction ComponentName({ propName }) {}
jsx
function Greeting(props) { return <h1>Hello, {props.name}!</h1>; } // Usage <Greeting name="Alice" />
Output
Hello, Alice!
Example
This example shows a Greeting component receiving a name prop and displaying a personalized message.
jsx
import React from 'react'; import { createRoot } from 'react-dom/client'; function Greeting({ name }) { return <h1>Hello, {name}!</h1>; } function App() { return ( <div> <Greeting name="Alice" /> <Greeting name="Bob" /> </div> ); } const container = document.getElementById('root'); const root = createRoot(container); root.render(<App />);
Output
Hello, Alice!
Hello, Bob!
Common Pitfalls
Common mistakes when passing props include:
- Forgetting to use curly braces
{}for JavaScript values inside JSX attributes. - Trying to modify
propsinside the component (props are read-only). - Not destructuring props and then trying to access undefined variables.
jsx
function WrongExample(props) { // Wrong: trying to change props // props.name = 'Changed'; // This will cause an error // Wrong: missing curly braces for JS value return <h1>Hello, props.name!</h1>; // Renders literally 'props.name!' } function RightExample({ name }) { return <h1>Hello, {name}!</h1>; }
Quick Reference
| Concept | Usage | Notes |
|---|---|---|
| Passing props | Use curly braces for JS values | |
| Accessing props | function Comp(props) { props.propName } | Or destructure: function Comp({ propName }) |
| Props are read-only | Do not modify props inside component | Use state if you need to change values |
| Default props | function Comp({ propName = 'default' }) {} | Set default values in parameters |
Key Takeaways
Pass data to components by adding attributes to the component tag using curly braces for JavaScript values.
Access props inside functional components via the props object or by destructuring in the function parameters.
Props are read-only; never try to modify them inside the component.
Always use curly braces {} around JavaScript expressions in JSX attributes.
Set default prop values by using default parameters in the function signature.