![]()
In React function components, you don’t use this at all – this is a fundamental difference from class components. Here’s how to properly access props in function components:
Correct Usage in Function Components
1. Basic Props Access
// Function component - props come as parameter
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
// Usage
<Welcome name="Sarah" />
2. Destructuring Props (Recommended)
function Welcome({ name, age }) { // Destructure props directly
return (
<div>
<h1>Hello, {name}</h1>
<p>You are {age} years old</p>
</div>
);
}
Common Scenarios
3. Default Props
function Welcome({ name = 'Guest', age = 18 }) {
// Default values if props not provided
return <h1>Hello, {name} ({age})</h1>;
}
4. Rest Props Pattern
function Input({ label, ...inputProps }) {
// inputProps contains all other props except label
return (
<div>
<label>{label}</label>
<input {...inputProps} />
</div>
);
}
// Usage
<Input label="Username" type="text" placeholder="Enter username" />
Converting from Class to Function Components
5. Class to Function Conversion
// Class component
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
// Function component equivalent
function Welcome({ name }) {
return <h1>Hello, {name}</h1>;
}
6. With TypeScript
interface WelcomeProps {
name: string;
age?: number; // Optional prop
}
const Welcome: React.FC<WelcomeProps> = ({ name, age = 18 }) => {
return (
<div>
<h1>Hello, {name}</h1>
{age && <p>Age: {age}</p>}
</div>
);
};
Advanced Patterns
7. Props with Children
function Card({ title, children }) {
return (
<div className="card">
<h2>{title}</h2>
<div className="content">
{children} {/* Access children via props */}
</div>
</div>
);
}
// Usage
<Card title="Profile">
<p>User details here</p>
</Card>
8. Forwarding Refs
const FancyInput = React.forwardRef((props, ref) => {
return <input ref={ref} {...props} />;
});
// Usage
const inputRef = useRef();
<FancyInput ref={inputRef} placeholder="Focus me" />;
Troubleshooting Checklist
- [ ] Verify you’re using a function component (not class)
- [ ] Check props are received as parameter
- [ ] Ensure no
thiskeyword is used - [ ] Validate prop names match between parent and child
- [ ] Confirm proper destructuring if used
- [ ] Check TypeScript interfaces if applicable
Common Mistakes
- Using
this.propsin function components - Misspelling prop names when destructuring
- Forgetting to pass props from parent component
- Confusing props and state concepts
- Omitting default values for optional props
Best Practices
- Always destructure props for cleaner code
- Use TypeScript/PropTypes for prop validation
- Provide default values for optional props
- Keep props immutable – don’t modify them
- Use meaningful prop names that describe their purpose
