0
0
React Nativemobile~5 mins

Children prop in React Native

Choose your learning style9 modes available
Introduction

The children prop lets you put content inside a component. It helps you reuse components with different inner parts.

You want to create a button component that can show different text or icons inside.
You build a card component that can hold any content like images, text, or buttons.
You want to wrap some UI elements with a container that adds style or behavior.
You create a layout component that arranges whatever children you put inside it.
Syntax
React Native
function MyComponent(props) {
  return <View>{props.children}</View>;
}

The children prop contains whatever you put between the component's opening and closing tags.

You access it with props.children inside the component.

Examples
This Box component wraps its children with padding and border.
React Native
function Box(props) {
  return <View style={{padding: 10, borderWidth: 1}}>{props.children}</View>;
}

// Usage:
<Box><Text>Hello</Text></Box>
Using destructuring to get children directly from props.
React Native
function Container({children}) {
  return <View style={{margin: 20}}>{children}</View>;
}

// Usage:
<Container>
  <Text>First</Text>
  <Text>Second</Text>
</Container>
Sample App

This app shows a white card in the center with a bold title and some text inside. The card uses the children prop to display whatever is placed inside it.

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

function Card(props) {
  return (
    <View style={styles.card}>
      {props.children}
    </View>
  );
}

export default function App() {
  return (
    <View style={styles.container}>
      <Card>
        <Text style={styles.title}>Welcome</Text>
        <Text>This is inside the card.</Text>
      </Card>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#f0f0f0'
  },
  card: {
    backgroundColor: 'white',
    padding: 20,
    borderRadius: 8,
    shadowColor: '#000',
    shadowOpacity: 0.2,
    shadowRadius: 5,
    shadowOffset: { width: 0, height: 2 },
    elevation: 3
  },
  title: {
    fontSize: 18,
    fontWeight: 'bold',
    marginBottom: 10
  }
});
OutputSuccess
Important Notes

You can put any React elements inside children, like text, images, or other components.

If no children are passed, props.children will be undefined or empty.

Using children makes your components flexible and reusable.

Summary

The children prop holds the content inside a component's tags.

Access children with props.children or by destructuring.

Children let you create flexible components that wrap any content.