Components and Props in React
1. Introduction
React is a popular JavaScript library for building user interfaces. At the core of React are components and props.
2. Components
Components are the building blocks of any React application. They allow you to split the UI into independent, reusable pieces.
2.1 Types of Components
- Functional Components: These are JavaScript functions that return React elements. They can accept props as arguments.
- Class Components: These are ES6 classes that extend from
React.Component
and must have a render method.
2.2 Example of a Functional Component
function Greeting(props) {
return <h1>Hello, {props.name}!</h1>;
}
2.3 Example of a Class Component
class Greeting extends React.Component {
render() {
return <h1>Hello, {this.props.name}!</h1>;
}
}
3. Props
Props, or properties, are a way to pass data from one component to another. They are read-only and help make components more dynamic.
3.1 Using Props
Props can be used to pass data into components. Here’s how you can use them:
function App() {
return <Greeting name="John"/>;
}
3.2 Props Validation
Using PropTypes
helps validate the data types of props passed to components.
import PropTypes from 'prop-types';
Greeting.propTypes = {
name: PropTypes.string.isRequired
};
4. Best Practices
When working with components and props, consider the following best practices:
- Keep components small and focused.
- Use props to pass data and callbacks down to child components.
- Utilize PropTypes for props validation.
- Use defaultProps to define default values for props.
5. FAQ
What is the difference between props and state?
Props are read-only and passed from parent to child, while state is managed within the component and can be changed.
Can props be modified?
No, props cannot be modified. They are immutable in terms of the component receiving them.
How do I pass functions as props?
You can pass functions as props just like any other data type, allowing child components to trigger actions in parent components.