Build: Greeting Screen
This screen shows a greeting message using a child component that receives the user's name as a prop.
Target UI
--------------------- | Greeting Screen | |-------------------| | Hello, Alice! | | | ---------------------
--------------------- | Greeting Screen | |-------------------| | Hello, Alice! | | | ---------------------
import React from 'react'; import { View, Text, StyleSheet } from 'react-native'; export default function GreetingScreen() { return ( <View style={styles.container}> {/* TODO: Add GreetingMessage component here and pass the name prop */} </View> ); } function GreetingMessage(props) { return ( <Text style={styles.greetingText}> {/* TODO: Display greeting message using props.name */} </Text> ); } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', }, greetingText: { fontSize: 24, fontWeight: 'bold', }, });
import React from 'react'; import { View, Text, StyleSheet } from 'react-native'; export default function GreetingScreen() { return ( <View style={styles.container}> <GreetingMessage name="Alice" /> </View> ); } function GreetingMessage(props) { return ( <Text style={styles.greetingText}> Hello, {props.name}! </Text> ); } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', }, greetingText: { fontSize: 24, fontWeight: 'bold', }, });
We created a parent component GreetingScreen that renders the child component GreetingMessage. We passed the string "Alice" as a prop named name to GreetingMessage. Inside GreetingMessage, we accessed props.name and displayed it inside the Text component with a friendly greeting. This shows how data flows from parent to child using props in React Native.
--------------------- | Greeting Screen | |-------------------| | Hello, Alice! | | | ---------------------
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