Passing Properties to Components
Tutorial: Passing Properties to Components
In this tutorial, you’ll learn how to use React's props to create dynamic and reusable components. This is essential for building scalable React applications by passing unique data to each component.
What You Will Learn
- How to use JSX properties to pass data to components.
- The difference between props and state in React.
- How to dynamically render components with unique data.
Steps to Use Props in Components
1. Understand Props vs. State
- Props: Immutable data passed from parent to child components.
- State: Data managed within a component that can change over time.
2. Define Props in JSX
Add properties to your PortfolioItem
component instances:
<PortfolioItem img="cabin" />
<PortfolioItem img="cake" />
<PortfolioItem img="circus" />
<PortfolioItem img="game" />
<PortfolioItem img="safe" />
<PortfolioItem img="submarine" />
3. Access Props in the Component
Use the this.props
object to access the data passed to the component:
class PortfolioItem extends React.Component {
render() {
const path = `img/portfolio/${this.props.img}.jpg`;
return (
<div className="portfolio-item">
<img src={path} alt={this.props.img} />
<div className="overlay">{this.props.img}</div>
</div>
);
}
}
- Template Literals: Use backticks (
`
) to dynamically insert the prop value into the path.
4. Dynamic Rendering
Now, each PortfolioItem
component will display a unique image based on the img
prop.
Common Pitfalls and Tips
- Default Values for Props:
Use default props to ensure a fallback value:
PortfolioItem.defaultProps = {
img: 'default'
};
- Prop Validation:
Ensure the correct type of data is passed usingPropTypes
:
import PropTypes from 'prop-types';
PortfolioItem.propTypes = {
img: PropTypes.string.isRequired
};
Summary
By passing props, you’ve made your components more dynamic and reusable. Each instance of PortfolioItem
can now display unique data, reducing redundancy and improving maintainability.
In the next lesson, you’ll learn how to pass entire components as props, further expanding your React knowledge.
Ready to Level Up Your Skills?
Join thousands of learners on 02GEEK and start your journey to becoming a coding expert today!
Enroll Now for Free!