๐ง What are Props?
Props, short for properties, are like arguments you pass to a function, but for components. They allow you to customize and reuse components by assigning them different values. Let’s imagine you have a Greeting component. With props, you can greet anyone you want just by changing the name.
<Greeting name="Alice" />
<Greeting name="Bob" />
Each time, the component displays a personalized message. That’s the magic of props.
๐ How to Use Props in React Native?
Here's a simple example.
๐จ๐ฉ๐ง๐ฆ Parent Component
import React from 'react';
import { View } from 'react-native';
import Greeting from './Greeting';
const App = () => {
return (
<View>
<Greeting name="Alice" />
<Greeting name="Bob" />
</View>
);
};
export default App;
๐ถ Child Component (Greeting)
import React from 'react';
import { Text } from 'react-native';
const Greeting = (props) => {
return <Text>Hello, {props.name}!</Text>;
};
export default Greeting;
Now, this component will display.
Hello, Alice!
Hello, Bob!
๐งน Cleaner Code with Destructuring
You can make the child component cleaner by using destructuring
const Greeting = ({ name }) => {
return <Text>Hello, {name}!</Text>;
};
โ
Why Use Props?
- ๐งฉ Reusable Components: One component, many uses.
- ๐ฌ Pass Data Down: Share information from parent to child.
- ๐ Read-Only: Props are not meant to be changed by the child.
๐ก Bonus: Type Checking with PropTypes
While not required, it's good practice to validate your props using the prop-types library.
npm install prop-types
import PropTypes from 'prop-types';
Greeting.propTypes = {
name: PropTypes.string.isRequired,
};
๐งฐ Default Props
What if no name is passed? Use defaultProps.
Greeting.defaultProps = {
name: 'Guest',
};
Now your app won’t break and will display “Hello, Guest!” by default.
๐ก Real-World Example
Let’s say you're building a custom button.
const CustomButton = ({ title, onPress }) => (
<TouchableOpacity onPress={onPress}>
<Text>{title}</Text>
</TouchableOpacity>
);
Use it like this.
<CustomButton title="Click Me" onPress={() => alert('Hello!')} />
๐ฆ Recap
- Props are inputs to components.
- They make components dynamic and reusable.
- Always pass props from parent to child.
- Use PropTypes and defaultProps for better code quality.
๐ Final Thoughts
Props in React Native are one of the simplest yet most powerful concepts you'll use when building mobile apps. By understanding how to pass props between components, you can create a highly reusable, flexible, and maintainable UI.
Ready to take your skills to the next level? Learn more about advanced concepts like props.children, or how to combine props and state to build dynamic and interactive components in React Native.