0
0
React Nativemobile~5 mins

Custom components in React Native

Choose your learning style9 modes available
Introduction

Custom components help you reuse code and build your app faster. They let you create your own building blocks for the app's look and behavior.

You want to show the same button style in many places.
You need a special header that appears on multiple screens.
You want to organize your app into smaller, easy-to-understand parts.
You want to add custom behavior to a group of UI elements.
You want to keep your code clean and avoid repeating yourself.
Syntax
React Native
function MyComponent(props) {
  return (
    <View>
      <Text>{props.title}</Text>
    </View>
  );
}

Custom components are just functions that return UI elements.

You can pass data to them using props.

Examples
A simple component that shows a greeting.
React Native
function Greeting() {
  return <Text>Hello!</Text>;
}
This component uses a prop to show a personalized greeting.
React Native
function Greeting(props) {
  return <Text>Hello, {props.name}!</Text>;
}
Same as above but using arrow function and destructuring props.
React Native
const Greeting = ({ name }) => <Text>Hello, {name}!</Text>;
Sample App

This app shows two cards using the CustomCard component. Each card has a title and description. The cards have simple styling and accessibility labels.

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

function CustomCard({ title, description }) {
  return (
    <View style={styles.card} accessible={true} accessibilityLabel={title}>
      <Text style={styles.title}>{title}</Text>
      <Text style={styles.description}>{description}</Text>
    </View>
  );
}

export default function App() {
  return (
    <View style={styles.container}>
      <CustomCard title="Welcome" description="This is a custom card component." />
      <CustomCard title="React Native" description="Build mobile apps with JavaScript." />
    </View>
  );
}

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

Always give your components clear names that describe what they do.

Use props to make components flexible and reusable.

Remember to add accessibility labels for better app usability.

Summary

Custom components let you build reusable UI pieces.

They are simple functions that return UI elements.

Use props to pass data and customize components.