The basic concept of props (Properties) is the same as that of
React for the web. They serve as a way data is passed from a parent to a child
component.
This article will examine how props work in React Native apps and
provide examples with functional components.
Props are used to pass values between components in React Native. It allows us
to change the behavior and appearance of the child component.
- Unidirectional Data Flow: Data flows from parent to child components via props, as in React web.
- Read-Only: Props cannot be changed within the child component that receives them. You should never directly modify props in the child component. If a child needs to communicate changes to the parent, you typically pass down a function as a prop from the parent, which the child can then invoke.
- Configuration: Props enable child components to be flexible and reusable in a variety of scenarios.
Let's look at some examples.
Example #1
We've created a simple reusable component that displays a personalized
message. Here's our GreetMe component. In the component, we used the
propName type to pass the name prop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type propName = { name: string }; | |
const GreetMe = (_name: propName) => { | |
return ( | |
<View> | |
<Text style={styles.text}>Hello, {_name.name}!</Text> | |
</View> | |
); | |
}; | |
export default GreetMe; | |
const styles = StyleSheet.create({ | |
container: { | |
flex: 1, | |
justifyContent: "center", | |
paddingHorizontal: 10, | |
}, | |
text: { | |
fontSize: 20, | |
fontWeight: "bold", | |
}, | |
}); |
Here's our parent component, which makes use of the GreetMe component.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const GreetingExample = () => { | |
return ( | |
<View style={styles.container}> | |
<GreetMe name="Alice" /> | |
<GreetMe name="Bob" /> | |
<GreetMe name="Charlie" /> | |
</View> | |
); | |
}; | |
export default GreetingExample; | |
const styles = StyleSheet.create({ | |
container: { | |
flex: 1, | |
justifyContent: "center", | |
paddingHorizontal: 10, | |
}, | |
}); |
In the parent component, the GreetMe component is used several times.
Each GreetMe instance is assigned a unique name prop.
Example #2
Props can be of various data types, such as numbers, booleans, arrays,
objects, styles, and functions. We have passed different types of props into
the component.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type User = { | |
name: string; | |
age: number; | |
isPro: boolean; | |
favoriteColors: any[]; | |
}; | |
type propCard = { user: User; onButtonPress: any; cardStyle: any }; | |
const UserCard = (props: propCard) => { | |
return ( | |
<View style={[styles.card, props.cardStyle]}> | |
<Text style={styles.name}>{props.user.name}</Text> | |
<Text>Age: {props.user.age}</Text> | |
{props.user.isPro && <Text style={styles.proBadge}>Pro User</Text>} | |
<Text>Favorite Colors: {props.user.favoriteColors.join(", ")}</Text> | |
<TouchableOpacity style={styles.button} onPress={props.onButtonPress}> | |
<Text style={styles.buttonText}>View Profile</Text> | |
</TouchableOpacity> | |
</View> | |
); | |
}; | |
export default UserCard; | |
const styles = StyleSheet.create({ | |
card: { | |
backgroundColor: "#f0f0f0", | |
padding: 20, | |
marginVertical: 10, | |
borderRadius: 8, | |
width: "80%", | |
alignItems: "center", | |
}, | |
name: { | |
fontSize: 18, | |
fontWeight: "bold", | |
marginBottom: 5, | |
}, | |
proBadge: { | |
color: "gold", | |
fontWeight: "bold", | |
marginTop: 5, | |
}, | |
button: { | |
backgroundColor: "#007bff", | |
padding: 10, | |
borderRadius: 5, | |
marginTop: 10, | |
}, | |
buttonText: { | |
color: "white", | |
fontWeight: "bold", | |
}, | |
}); |
This component makes use of these props to display various information.
Here's our parent component, which uses the UserCard component.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const PropExample2 = () => { | |
const firstUser: User = { | |
name: "David", | |
age: 25, | |
isPro: false, | |
favoriteColors: ["Blue", "Green"], | |
}; | |
const secondUser: User = { | |
name: "Eve", | |
age: 32, | |
isPro: false, | |
favoriteColors: ["Red", "Black", "White"], | |
}; | |
const onButtonPress = (userName: any) => { | |
Alert.alert(`Viewing profile for ${userName}`); | |
}; | |
return ( | |
<View style={styles.container}> | |
<UserCard | |
user={firstUser} | |
onButtonPress={() => onButtonPress(firstUser.name)} | |
cardStyle={{ borderColor: "gold", borderWidth: 2 }} | |
/> | |
<UserCard | |
user={secondUser} | |
onButtonPress={() => onButtonPress(secondUser.name)} | |
cardStyle={undefined} | |
/> | |
</View> | |
); | |
}; | |
export default PropExample2; | |
const styles = StyleSheet.create({ | |
container: { | |
flex: 1, | |
justifyContent: "center", | |
alignItems: "center", | |
}, | |
}); |
We passed the User object to the component's user prop. The
function is assigned to the onButtonPress property. Here, a function is
passed as a prop to allow the child to cause an action in the parent.
Example #3
This example shows how props can be used to bind data to a list component.
FlatList is a useful component for efficiently rendering lists of data.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export type Item = { | |
id: number; | |
name: string; | |
description: string; | |
}; | |
type propData = { items: Item[] }; | |
const DataList = (data: propData) => { | |
const renderItem = ({ item }: { item: Item }) => ( | |
<View style={styles.itemContainer}> | |
<Text style={styles.itemText}>{item.name}</Text> | |
<Text style={styles.itemDescription}>{item.description}</Text> | |
</View> | |
); | |
return ( | |
<FlatList | |
data={data.items} | |
renderItem={renderItem} | |
keyExtractor={(item) => item.id.toString()} | |
/> | |
); | |
}; | |
export default DataList; | |
const styles = StyleSheet.create({ | |
itemContainer: { | |
backgroundColor: "white", | |
padding: 15, | |
marginVertical: 8, | |
marginHorizontal: 16, | |
borderRadius: 5, | |
elevation: 2, | |
shadowColor: "#000", | |
shadowOffset: { width: 0, height: 2 }, | |
shadowOpacity: 0.1, | |
shadowRadius: 2, | |
}, | |
itemText: { | |
fontSize: 18, | |
fontWeight: "bold", | |
}, | |
itemDescription: { | |
fontSize: 14, | |
color: "#666", | |
}, | |
}); |
To display an array of data, we can pass it to FlatList's data prop.
And the renderItem prop specifies how to render each item in the list.
We have a custom renderItem that defines how each item will display
data. The item array renders the data as a View with
Text elements. The keyExtractor prop generates a unique key for
each list item. This is critical for FlatList's performance optimization.
Our parent used this child component for data binding.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const PropExample5 = () => { | |
const data: Item[] = [ | |
{ | |
id: 1, | |
name: "Solar Lantern", | |
description: | |
"A compact, solar-powered lantern ideal for outdoor camping and emergency use.", | |
}, | |
{ | |
id: 2, | |
name: "Wireless Earbuds", | |
description: | |
"Compact Bluetooth earbuds with noise cancellation and 8-hour battery life.", | |
}, | |
{ | |
id: 3, | |
name: "Travel Backpack", | |
description: | |
"Water-resistant backpack with multiple compartments and padded laptop sleeve.", | |
}, | |
{ | |
id: 4, | |
name: "Digital Alarm Clock", | |
description: | |
"LED display clock with customizable alarm tones and ambient light settings.", | |
}, | |
{ | |
id: 5, | |
name: "Foldable Yoga Mat", | |
description: | |
"Lightweight and foldable mat with anti-slip surface, great for yoga and Pilates.", | |
}, | |
]; | |
return ( | |
<View> | |
<DataList items={data} /> | |
</View> | |
); | |
}; | |
export default PropExample5; | |
const styles = StyleSheet.create({ | |
container: { | |
flex: 1, | |
paddingTop: 20, | |
backgroundColor: "#f0f0f0", | |
}, | |
}); |
DataList is a component that is specifically intended to render a list.
The items prop accepts an array of objects as input. The data source
for the FlatList component within the DataList component is the
items prop.
Example #4
In this example, we will look at how to use children prop to
create React Native components. This prop is useful for making container and
wrapper components.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const Container = (props: any) => { | |
return <View style={[styles.container, props.style]}>{props.children}</View>; | |
}; | |
export default Container; | |
const styles = StyleSheet.create({ | |
container: { | |
borderWidth: 1, | |
borderColor: "#ccc", | |
padding: 10, | |
margin: 10, | |
}, | |
}); |
The parent employs the Container component.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const PropExample3 = () => { | |
return ( | |
<View> | |
<Container style={{ backgroundColor: "#e0e0e0" }}> | |
<Text>This text is inside the container.</Text> | |
<Button title="Click Me" onPress={() => alert("Button clicked!")} /> | |
</Container> | |
<Container> | |
<Text>Another container with different content.</Text> | |
</Container> | |
</View> | |
); | |
}; | |
export default PropExample3; | |
const styles = StyleSheet.create({ | |
appContainer: { | |
flex: 1, | |
justifyContent: "center", | |
alignItems: "center", | |
}, | |
}); |
The Container component is designed to wrap other components. The
Container receives the Text and Button elements as its children.
The Container component retrieves these elements from
props.children and renders them in its View element.
These examples show how props are commonly used in React Native. We can use it
to pass values, control styling, and handle events. It can also be used to
transmit data that is used as a data source by the components. It allows us to
create dynamic UI and highly reusable components.
You can get the source code from
here.
Happy coding!!! 😊