0
0
React Nativemobile~5 mins

Props passing in React Native

Choose your learning style9 modes available
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.

You want to show a user's name inside a greeting message component.
You need to reuse a button component but with different labels.
You want to pass a color choice to a box component to change its background.
You want to send a number to a counter component to start counting from that number.
Syntax
React Native
function ChildComponent(props) {
  return <Text>{props.message}</Text>;
}

function ParentComponent() {
  return <ChildComponent message="Hello!" />;
}
Props are like function arguments but for components.
You can pass any data type as props: text, numbers, functions, or objects.
Examples
This sends the name "Anna" to the Greeting component, which shows "Hello, Anna!".
React Native
function Greeting(props) {
  return <Text>Hello, {props.name}!</Text>;
}

<Greeting name="Anna" />
The ColorBox uses the color prop to set its background color.
React Native
function ColorBox(props) {
  return <View style={{backgroundColor: props.color, width: 100, height: 100}} />;
}

<ColorBox color="blue" />
This button shows "Click me" and runs a function when pressed.
React Native
function Button(props) {
  return <TouchableOpacity onPress={props.onPress}>
    <Text>{props.label}</Text>
  </TouchableOpacity>;
}

<Button label="Click me" onPress={() => Alert.alert('Pressed!')} />
Sample App

This app shows a welcome message using a prop called username. It also has a button that shows an alert when pressed.

React Native
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>
  );
}
OutputSuccess
Important Notes

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.

Summary

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.