Props

Props is how react components communicate with each other. Every parent component can pass information to its child components by giving them props.

We've already seen props (short for properties) before, like how we pass in onPress is passed to the Button component, or how the styles is passed to the View component. Just like how functions can take in arguments, components can take in properties.

import React from 'react';
import { View, Text, Button } from 'react-native';

// Child component
const Greeting = (props) => {
  return (
    <View>
      <Text>Hello, {props.name}!</Text>
    </View>
  );
};

// Parent component
const App = () => {
  return (
    <View style={styles.container}>
      <Greeting name="Alice" />
      <Greeting name="Bob" />
      <Greeting name="Charlie" />
    </View>
  );
};

You can also pass functions as props!

import React from 'react';
import { View, Button } from 'react-native';

// Child component
const MyButton = (props) => {
  return (
    <Button title={props.title} onPress={props.onPress} />
  );
};

// Parent component
const App = () => {
  const handlePress = () => {
    alert('Button was pressed!');
  };

  return (
    <View>
      <MyButton title="Press Me" onPress={handlePress} />
    </View>
  );
};

In this example, the MyButton component receives a title and an onPress function as props from the parent App component. When the button is pressed, it triggers the handlePress function in the parent component.

Instead of using props, you can destructure the arguments directly in the function signature. This makes it clear which props the component expects and avoids the need to repeatedly write props.

import React from 'react';
import { View, Button } from 'react-native';

// Child component using destructuring
const MyButton = ({ title, onPress }) => {
  return (
    <Button title={title} onPress={onPress} />
  );
};

// Parent component
const App = () => {
  const handlePress = () => {
    alert('Button was pressed!');
  };

  return (
    <View style={styles.container}>
      <MyButton title="Press Me" onPress={handlePress} />
    </View>
  );
};

Last updated