Introduction
Props let you send information from one part of your app to another. This helps different parts work together and show the right data.
Props let you send information from one part of your app to another. This helps different parts work together and show the right data.
function ChildComponent(props) {
return <Text>{props.message}</Text>;
}
function ParentComponent() {
return <ChildComponent message="Hello!" />;
}function Greeting(props) {
return <Text>Hello, {props.name}!</Text>;
}
<Greeting name="Anna" />function ColorBox(props) {
return <View style={{backgroundColor: props.color, width: 100, height: 100}} />;
}
<ColorBox color="blue" />function Button(props) {
return <TouchableOpacity onPress={props.onPress}>
<Text>{props.label}</Text>
</TouchableOpacity>;
}
<Button label="Click me" onPress={() => Alert.alert('Pressed!')} />This app shows a welcome message using a prop called username. It also has a button that shows an alert when pressed.
import React from 'react'; import { Text, View, TouchableOpacity, Alert } from 'react-native'; function WelcomeMessage(props) { return <Text style={{fontSize: 20}}>Welcome, {props.username}!</Text>; } export default function App() { return ( <View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}> <WelcomeMessage username="Sam" /> <TouchableOpacity onPress={() => Alert.alert('Button pressed!')} style={{marginTop: 20, backgroundColor: '#4CAF50', padding: 10, borderRadius: 5}} accessibilityLabel="Press this button" > <Text style={{color: 'white'}}>Press me</Text> </TouchableOpacity> </View> ); }
Props are read-only. You cannot change them inside the child component.
Always name props clearly so others understand what data is expected.
Use accessibilityLabel on touchable elements for better accessibility.
Props pass data from parent to child components.
They help make components reusable and dynamic.
Props are like inputs that components use to show or do different things.
props in React Native components?title with value "Hello" to a component Greeting?title="Hello".function Welcome(props) {
return {props.message};
}
export default function App() {
return ;
}Welcome component receives message prop and displays it inside Text.App component passes message="Hi there!" to Welcome.function Button(props) {
return {props.label};
}
export default function App() {
return ;
}label is passed as label=ClickMe without quotes, which is invalid for strings.label="ClickMe" or in curly braces if variable.Profile component that shows a user's name and age. Which of these is the best way to pass props to make it flexible?name should be in quotes; numbers like age should be passed as JavaScript expressions using curly braces.name as string and age as number. <Profile name={"Alice"} age="30" /> passes age as string which is less ideal. <Profile name=Alice age=30 /> misses quotes and braces. <Profile name={Alice} age={30} /> uses undefined variable Alice.Pass the test and this pattern moves unknown