How to create fully functional eCommerce React Native Mobile App?

nadim_ch0wdhury

Nadim Chowdhury

Posted on June 25, 2024

How to create fully functional eCommerce React Native Mobile App?

Creating fully functional code with proper styling for an ecommerce mobile app using React Native involves several components and functionalities. Here, I'll provide simplified code snippets for the Authentication and User Management section, as well as the Product Listings section. Please note that styling (CSS or similar) isn't directly applicable in React Native; instead, we use components and stylesheets directly in JavaScript.

Authentication and User Management

User Registration and Login

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

const AuthScreen = () => {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');

  const handleLogin = () => {
    // Logic for handling login (e.g., API call)
    console.log('Logging in with:', email, password);
  };

  const handleRegister = () => {
    // Logic for handling registration (e.g., API call)
    console.log('Registering with:', email, password);
  };

  return (
    <View style={styles.container}>
      <Text style={styles.label}>Email:</Text>
      <TextInput
        style={styles.input}
        value={email}
        onChangeText={setEmail}
        placeholder="Enter your email"
        keyboardType="email-address"
        autoCapitalize="none"
      />
      <Text style={styles.label}>Password:</Text>
      <TextInput
        style={styles.input}
        value={password}
        onChangeText={setPassword}
        placeholder="Enter your password"
        secureTextEntry
      />
      <View style={styles.buttonContainer}>
        <Button title="Login" onPress={handleLogin} />
        <Button title="Register" onPress={handleRegister} />
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    paddingHorizontal: 20,
  },
  label: {
    fontSize: 16,
    fontWeight: 'bold',
    marginBottom: 5,
  },
  input: {
    width: '100%',
    height: 40,
    borderWidth: 1,
    borderColor: '#ccc',
    paddingHorizontal: 10,
    marginBottom: 10,
  },
  buttonContainer: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    width: '100%',
    marginTop: 20,
  },
});

export default AuthScreen;
Enter fullscreen mode Exit fullscreen mode

User Profile Management

For user profile management, you would typically navigate to a different screen where users can edit their profile details, change passwords, etc. Here’s a basic outline:

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

const ProfileScreen = () => {
  const handleUpdateProfile = () => {
    // Logic for updating profile (e.g., API call)
    console.log('Updating profile...');
  };

  const handleChangePassword = () => {
    // Logic for changing password (e.g., API call)
    console.log('Changing password...');
  };

  return (
    <View style={styles.container}>
      <Text style={styles.label}>Edit Profile</Text>
      <TextInput style={styles.input} placeholder="Full Name" />
      <TextInput style={styles.input} placeholder="Email Address" />
      <View style={styles.buttonContainer}>
        <Button title="Update Profile" onPress={handleUpdateProfile} />
      </View>

      <Text style={styles.label}>Change Password</Text>
      <TextInput
        style={styles.input}
        placeholder="Current Password"
        secureTextEntry
      />
      <TextInput
        style={styles.input}
        placeholder="New Password"
        secureTextEntry
      />
      <View style={styles.buttonContainer}>
        <Button title="Change Password" onPress={handleChangePassword} />
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    paddingHorizontal: 20,
  },
  label: {
    fontSize: 16,
    fontWeight: 'bold',
    marginBottom: 10,
    alignSelf: 'flex-start',
    marginTop: 20,
  },
  input: {
    width: '100%',
    height: 40,
    borderWidth: 1,
    borderColor: '#ccc',
    paddingHorizontal: 10,
    marginBottom: 10,
  },
  buttonContainer: {
    width: '100%',
    marginTop: 10,
  },
});

export default ProfileScreen;
Enter fullscreen mode Exit fullscreen mode

Product Listings

Display Categories and Subcategories

import React, { useState, useEffect } from 'react';
import { View, Text, FlatList, StyleSheet } from 'react-native';

const ProductListScreen = () => {
  const [products, setProducts] = useState([]);

  useEffect(() => {
    // Simulated data fetch (replace with actual API call)
    const fetchData = async () => {
      // Example API call
      const response = await fetch('https://api.example.com/products');
      const data = await response.json();
      setProducts(data);
    };

    fetchData();
  }, []);

  return (
    <View style={styles.container}>
      <FlatList
        data={products}
        keyExtractor={(item) => item.id.toString()}
        renderItem={({ item }) => (
          <View style={styles.productContainer}>
            <Text style={styles.productName}>{item.name}</Text>
            <Text style={styles.productPrice}>${item.price}</Text>
          </View>
        )}
      />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    paddingHorizontal: 20,
    paddingTop: 20,
  },
  productContainer: {
    borderWidth: 1,
    borderColor: '#ccc',
    borderRadius: 8,
    padding: 10,
    marginBottom: 10,
  },
  productName: {
    fontSize: 16,
    fontWeight: 'bold',
  },
  productPrice: {
    fontSize: 14,
    color: 'green',
  },
});

export default ProductListScreen;
Enter fullscreen mode Exit fullscreen mode

Product Search Functionality

To implement product search functionality, you would typically add a search bar and handle filtering of products based on user input. Here's a basic example:

import React, { useState } from 'react';
import { View, TextInput, FlatList, Text, StyleSheet } from 'react-native';

const ProductSearchScreen = ({ products }) => {
  const [searchQuery, setSearchQuery] = useState('');
  const [filteredProducts, setFilteredProducts] = useState([]);

  const handleSearch = () => {
    const filtered = products.filter(
      (product) =>
        product.name.toLowerCase().includes(searchQuery.toLowerCase())
    );
    setFilteredProducts(filtered);
  };

  return (
    <View style={styles.container}>
      <TextInput
        style={styles.input}
        value={searchQuery}
        onChangeText={setSearchQuery}
        placeholder="Search for products..."
        onSubmitEditing={handleSearch}
      />
      <FlatList
        data={filteredProducts}
        keyExtractor={(item) => item.id.toString()}
        renderItem={({ item }) => (
          <View style={styles.productContainer}>
            <Text style={styles.productName}>{item.name}</Text>
            <Text style={styles.productPrice}>${item.price}</Text>
          </View>
        )}
      />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    paddingHorizontal: 20,
    paddingTop: 20,
  },
  input: {
    height: 40,
    borderWidth: 1,
    borderColor: '#ccc',
    paddingHorizontal: 10,
    marginBottom: 10,
  },
  productContainer: {
    borderWidth: 1,
    borderColor: '#ccc',
    borderRadius: 8,
    padding: 10,
    marginBottom: 10,
  },
  productName: {
    fontSize: 16,
    fontWeight: 'bold',
  },
  productPrice: {
    fontSize: 14,
    color: 'green',
  },
});

export default ProductSearchScreen;
Enter fullscreen mode Exit fullscreen mode

These code snippets provide a foundational structure for implementing authentication, user management, and product listings functionalities in a React Native ecommerce app. Remember to replace placeholders (like API endpoints, data handling) with your actual implementation logic as per your app's requirements.

Sure, I'll provide simplified code snippets for the Product Details and Shopping Cart functionalities in a React Native app. Remember, styling in React Native uses JavaScript and StyleSheet objects, not traditional CSS.

Product Details

Detailed Product Screen

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

const ProductDetailScreen = ({ route }) => {
  const { product } = route.params; // Assuming navigation param contains product details

  return (
    <ScrollView style={styles.container}>
      <Image source={{ uri: product.imageUrl }} style={styles.image} />
      <View style={styles.detailsContainer}>
        <Text style={styles.title}>{product.name}</Text>
        <Text style={styles.price}>${product.price}</Text>
        <Text style={styles.description}>{product.description}</Text>
        <Text style={styles.availability}>
          Availability: {product.available ? 'In Stock' : 'Out of Stock'}
        </Text>
        {/* Additional details like shipping information */}
      </View>
      {/* Add to cart button */}
      <View style={styles.addToCartContainer}>
        <Button title="Add to Cart" onPress={() => console.log('Added to cart:', product)} />
      </View>
    </ScrollView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    paddingHorizontal: 20,
    paddingTop: 20,
  },
  image: {
    width: '100%',
    height: 300,
    marginBottom: 20,
    resizeMode: 'cover',
  },
  detailsContainer: {
    marginBottom: 20,
  },
  title: {
    fontSize: 24,
    fontWeight: 'bold',
    marginBottom: 10,
  },
  price: {
    fontSize: 18,
    color: 'green',
    marginBottom: 10,
  },
  description: {
    fontSize: 16,
    marginBottom: 10,
  },
  availability: {
    fontSize: 16,
    marginBottom: 10,
  },
  addToCartContainer: {
    width: '100%',
    marginBottom: 20,
  },
});

export default ProductDetailScreen;
Enter fullscreen mode Exit fullscreen mode

Shopping Cart

Cart Screen

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

const CartScreen = () => {
  const [cartItems, setCartItems] = useState([
    { id: '1', name: 'Product 1', price: 50, quantity: 2 },
    { id: '2', name: 'Product 2', price: 30, quantity: 1 },
  ]);

  const handleRemoveItem = (itemId) => {
    const updatedCartItems = cartItems.filter(item => item.id !== itemId);
    setCartItems(updatedCartItems);
  };

  const handleAdjustQuantity = (itemId, newQuantity) => {
    const updatedCartItems = cartItems.map(item =>
      item.id === itemId ? { ...item, quantity: newQuantity } : item
    );
    setCartItems(updatedCartItems);
  };

  const getTotalPrice = () => {
    return cartItems.reduce((total, item) => total + item.price * item.quantity, 0);
  };

  return (
    <View style={styles.container}>
      <FlatList
        data={cartItems}
        keyExtractor={item => item.id}
        renderItem={({ item }) => (
          <View style={styles.cartItem}>
            <Text style={styles.itemName}>{item.name}</Text>
            <Text style={styles.itemPrice}>${item.price}</Text>
            <View style={styles.quantityContainer}>
              <Button title="-" onPress={() => handleAdjustQuantity(item.id, item.quantity - 1)} />
              <Text style={styles.quantity}>{item.quantity}</Text>
              <Button title="+" onPress={() => handleAdjustQuantity(item.id, item.quantity + 1)} />
              <Button title="Remove" onPress={() => handleRemoveItem(item.id)} />
            </View>
          </View>
        )}
      />
      <View style={styles.totalContainer}>
        <Text style={styles.totalLabel}>Total:</Text>
        <Text style={styles.totalPrice}>${getTotalPrice()}</Text>
      </View>
      <View style={styles.checkoutContainer}>
        <Button title="Proceed to Checkout" onPress={() => console.log('Proceed to checkout')} />
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    paddingHorizontal: 20,
    paddingTop: 20,
  },
  cartItem: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: 10,
    padding: 10,
    borderWidth: 1,
    borderColor: '#ccc',
    borderRadius: 8,
  },
  itemName: {
    fontSize: 18,
    fontWeight: 'bold',
  },
  itemPrice: {
    fontSize: 16,
  },
  quantityContainer: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  quantity: {
    marginHorizontal: 10,
    fontSize: 16,
  },
  totalContainer: {
    flexDirection: 'row',
    justifyContent: 'flex-end',
    marginTop: 20,
    borderTopWidth: 1,
    paddingTop: 10,
  },
  totalLabel: {
    fontSize: 18,
    fontWeight: 'bold',
    marginRight: 10,
  },
  totalPrice: {
    fontSize: 18,
    color: 'green',
  },
  checkoutContainer: {
    width: '100%',
    marginTop: 20,
  },
});

export default CartScreen;
Enter fullscreen mode Exit fullscreen mode

These code snippets provide a basic implementation of Product Details and Shopping Cart functionalities in a React Native app. They include handling product details display, adding/removing items to/from the cart, adjusting quantities, and displaying the total price with proper styling using React Native's built-in components and StyleSheet object. Adjust them as per your specific application logic and UI design requirements.

Implementing the Checkout Process and Order Management in a React Native app involves handling several screens and integrating with external services like payment gateways. Below, I'll provide simplified code snippets for these functionalities. Please note that integrating with real payment gateways requires additional setup and typically involves backend services to securely handle sensitive information.

Checkout Process

Shipping Address Selection Screen

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

const ShippingAddressScreen = ({ navigation }) => {
  const [fullName, setFullName] = useState('');
  const [address, setAddress] = useState('');
  const [city, setCity] = useState('');
  const [zipCode, setZipCode] = useState('');

  const handleContinue = () => {
    // Validate input fields (add validation logic as needed)
    if (!fullName || !address || !city || !zipCode) {
      alert('Please fill out all fields');
      return;
    }

    // Proceed to next screen (e.g., billing information)
    navigation.navigate('BillingInfo');
  };

  return (
    <View style={styles.container}>
      <Text style={styles.label}>Full Name:</Text>
      <TextInput
        style={styles.input}
        value={fullName}
        onChangeText={setFullName}
        placeholder="Enter your full name"
      />
      <Text style={styles.label}>Address:</Text>
      <TextInput
        style={styles.input}
        value={address}
        onChangeText={setAddress}
        placeholder="Enter your address"
        multiline
      />
      <Text style={styles.label}>City:</Text>
      <TextInput
        style={styles.input}
        value={city}
        onChangeText={setCity}
        placeholder="Enter your city"
      />
      <Text style={styles.label}>Zip Code:</Text>
      <TextInput
        style={styles.input}
        value={zipCode}
        onChangeText={setZipCode}
        placeholder="Enter your zip code"
        keyboardType="numeric"
      />
      <Button title="Continue" onPress={handleContinue} />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    paddingHorizontal: 20,
    paddingTop: 20,
  },
  label: {
    fontSize: 16,
    fontWeight: 'bold',
    marginBottom: 5,
  },
  input: {
    width: '100%',
    height: 40,
    borderWidth: 1,
    borderColor: '#ccc',
    paddingHorizontal: 10,
    marginBottom: 10,
  },
});

export default ShippingAddressScreen;
Enter fullscreen mode Exit fullscreen mode

Billing Information Entry Screen

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

const BillingInfoScreen = ({ navigation }) => {
  const [cardNumber, setCardNumber] = useState('');
  const [expiryDate, setExpiryDate] = useState('');
  const [cvv, setCvv] = useState('');

  const handlePayment = () => {
    // Validate input fields (add validation logic as needed)
    if (!cardNumber || !expiryDate || !cvv) {
      alert('Please fill out all fields');
      return;
    }

    // Implement payment gateway integration (simulate here)
    alert('Processing payment...');

    // Proceed to order summary screen (order confirmation)
    navigation.navigate('OrderSummary');
  };

  return (
    <View style={styles.container}>
      <Text style={styles.label}>Card Number:</Text>
      <TextInput
        style={styles.input}
        value={cardNumber}
        onChangeText={setCardNumber}
        placeholder="Enter your card number"
        keyboardType="numeric"
      />
      <Text style={styles.label}>Expiry Date:</Text>
      <TextInput
        style={styles.input}
        value={expiryDate}
        onChangeText={setExpiryDate}
        placeholder="MM/YYYY"
        keyboardType="numeric"
      />
      <Text style={styles.label}>CVV:</Text>
      <TextInput
        style={styles.input}
        value={cvv}
        onChangeText={setCvv}
        placeholder="Enter CVV"
        keyboardType="numeric"
        secureTextEntry
      />
      <Button title="Pay Now" onPress={handlePayment} />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    paddingHorizontal: 20,
    paddingTop: 20,
  },
  label: {
    fontSize: 16,
    fontWeight: 'bold',
    marginBottom: 5,
  },
  input: {
    width: '100%',
    height: 40,
    borderWidth: 1,
    borderColor: '#ccc',
    paddingHorizontal: 10,
    marginBottom: 10,
  },
});

export default BillingInfoScreen;
Enter fullscreen mode Exit fullscreen mode

Order Summary and Confirmation Screen

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

const OrderSummaryScreen = ({ navigation }) => {
  const handleFinishOrder = () => {
    // Simulated order completion
    alert('Order placed successfully!');

    // Navigate to order history or home screen
    navigation.navigate('Home');
  };

  return (
    <View style={styles.container}>
      <Text style={styles.title}>Order Summary</Text>
      {/* Display order details here */}
      <View style={styles.summaryContainer}>
        <Text>Order Total: $150</Text>
        <Text>Shipping Address: John Doe, 123 Main St, New York, NY 10001</Text>
        {/* Additional order details */}
      </View>
      <Button title="Finish Order" onPress={handleFinishOrder} />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    paddingHorizontal: 20,
    paddingTop: 20,
  },
  title: {
    fontSize: 24,
    fontWeight: 'bold',
    marginBottom: 20,
  },
  summaryContainer: {
    borderWidth: 1,
    borderColor: '#ccc',
    padding: 10,
    marginBottom: 20,
  },
});

export default OrderSummaryScreen;
Enter fullscreen mode Exit fullscreen mode

Order Management

Order History Screen

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

const OrderHistoryScreen = () => {
  const orders = [
    { id: '1', date: '2023-06-01', total: 100, status: 'Delivered' },
    { id: '2', date: '2023-05-25', total: 150, status: 'Processing' },
  ];

  return (
    <View style={styles.container}>
      <Text style={styles.title}>Order History</Text>
      <FlatList
        data={orders}
        keyExtractor={item => item.id}
        renderItem={({ item }) => (
          <View style={styles.orderContainer}>
            <Text>Order ID: {item.id}</Text>
            <Text>Date: {item.date}</Text>
            <Text>Total: ${item.total}</Text>
            <Text>Status: {item.status}</Text>
          </View>
        )}
      />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    paddingHorizontal: 20,
    paddingTop: 20,
  },
  title: {
    fontSize: 24,
    fontWeight: 'bold',
    marginBottom: 20,
  },
  orderContainer: {
    borderWidth: 1,
    borderColor: '#ccc',
    borderRadius: 8,
    padding: 10,
    marginBottom: 10,
  },
});

export default OrderHistoryScreen;
Enter fullscreen mode Exit fullscreen mode

Order Tracking (if applicable)

Implementing order tracking would typically involve integrating with a shipping service API and displaying real-time updates. Here's a simplified example structure:

// Example of order tracking could involve integrating with a shipping service API
// Displaying real-time updates would require actual implementation with APIs and data management
Enter fullscreen mode Exit fullscreen mode

Order Status Updates

// Typically handled by backend services updating order status
// Displaying real-time updates would require actual implementation with APIs and data management
Enter fullscreen mode Exit fullscreen mode

These code snippets provide a foundational structure for implementing Checkout Process and Order Management functionalities in a React Native ecommerce app. They cover basic screens for shipping address selection, billing information entry, order summary, and order history. Remember to replace placeholders (like API endpoints, data handling) with your actual implementation logic as per your app's requirements. Integrating with real payment gateways and shipping APIs would require additional setup and security considerations.

Implementing Wishlist and Notifications functionalities in a React Native app involves managing user preferences and integrating with push notification services. Below are simplified code snippets for these features:

Wishlist

Wishlist Screen

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

const WishlistScreen = () => {
  const [wishlist, setWishlist] = useState([
    { id: '1', name: 'Product 1', price: 50 },
    { id: '2', name: 'Product 2', price: 30 },
  ]);

  const handleRemoveFromWishlist = (itemId) => {
    const updatedWishlist = wishlist.filter(item => item.id !== itemId);
    setWishlist(updatedWishlist);
  };

  return (
    <View style={styles.container}>
      {wishlist.length === 0 ? (
        <Text style={styles.emptyText}>Your wishlist is empty.</Text>
      ) : (
        <FlatList
          data={wishlist}
          keyExtractor={item => item.id}
          renderItem={({ item }) => (
            <View style={styles.productContainer}>
              <Text style={styles.productName}>{item.name}</Text>
              <Text style={styles.productPrice}>${item.price}</Text>
              <Button
                title="Remove"
                onPress={() => handleRemoveFromWishlist(item.id)}
              />
            </View>
          )}
        />
      )}
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    paddingHorizontal: 20,
    paddingTop: 20,
  },
  emptyText: {
    fontSize: 18,
    textAlign: 'center',
    marginTop: 50,
  },
  productContainer: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: 10,
    padding: 10,
    borderWidth: 1,
    borderColor: '#ccc',
    borderRadius: 8,
  },
  productName: {
    fontSize: 16,
    fontWeight: 'bold',
  },
  productPrice: {
    fontSize: 14,
  },
});

export default WishlistScreen;
Enter fullscreen mode Exit fullscreen mode

Notifications

Push Notifications Setup (Using Expo Notifications)

First, ensure you have Expo installed and configured for your React Native project. Then, you can use Expo's Notifications module for handling push notifications.

import React, { useEffect } from 'react';
import { View, Text, Button, StyleSheet } from 'react-native';
import * as Notifications from 'expo-notifications';

const NotificationsScreen = () => {
  useEffect(() => {
    registerForPushNotifications(); // Register for push notifications when component mounts
  }, []);

  const registerForPushNotifications = async () => {
    // Check if permission is granted
    const { status } = await Notifications.requestPermissionsAsync();
    if (status !== 'granted') {
      alert('Permission to receive notifications was denied');
      return;
    }

    // Get the device's push token
    const token = (await Notifications.getExpoPushTokenAsync()).data;
    console.log('Push token:', token);
    // Send this token to your server
    // Save it to AsyncStorage or similar for later use
  };

  const handleLocalNotification = () => {
    Notifications.scheduleNotificationAsync({
      content: {
        title: 'Hello!',
        body: 'This is a local notification!',
      },
      trigger: {
        seconds: 5, // Notification will be triggered after 5 seconds
      },
    });
  };

  return (
    <View style={styles.container}>
      <Text style={styles.title}>Push Notifications</Text>
      <Button
        title="Send Local Notification"
        onPress={handleLocalNotification}
      />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    paddingHorizontal: 20,
    paddingTop: 20,
  },
  title: {
    fontSize: 24,
    fontWeight: 'bold',
    marginBottom: 20,
  },
});

export default NotificationsScreen;
Enter fullscreen mode Exit fullscreen mode

Explanation

  • Wishlist Screen: Allows users to view items they have saved for later purchase and remove items from the wishlist.
  • Notifications Screen: Demonstrates how to set up and send local notifications using Expo's Notifications module. For production use with push notifications, you'd need to handle server-side logic for sending notifications and managing tokens securely.

Make sure to integrate these functionalities into your React Native app according to your specific requirements and backend services for handling data storage, notifications, and user preferences.

Implementing Settings, Additional Features like Social Sharing, Customer Support Integration, and Analytics/Reporting in a React Native app involves various components and potentially integrating with third-party services. Below are simplified code snippets for these functionalities:

Settings

App Settings Screen

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

const SettingsScreen = () => {
  const [notificationsEnabled, setNotificationsEnabled] = useState(true);
  const [language, setLanguage] = useState('English');
  const [currency, setCurrency] = useState('USD');

  const handleNotificationsToggle = () => {
    setNotificationsEnabled(previousState => !previousState);
  };

  return (
    <View style={styles.container}>
      <Text style={styles.sectionTitle}>App Settings</Text>
      <View style={styles.settingItem}>
        <Text style={styles.settingLabel}>Notifications</Text>
        <Switch
          value={notificationsEnabled}
          onValueChange={handleNotificationsToggle}
        />
      </View>
      <View style={styles.settingItem}>
        <Text style={styles.settingLabel}>Language</Text>
        <Text style={styles.settingValue}>{language}</Text>
        {/* Add language selection functionality */}
      </View>
      <View style={styles.settingItem}>
        <Text style={styles.settingLabel}>Currency</Text>
        <Text style={styles.settingValue}>{currency}</Text>
        {/* Add currency selection functionality */}
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    paddingHorizontal: 20,
    paddingTop: 20,
  },
  sectionTitle: {
    fontSize: 24,
    fontWeight: 'bold',
    marginBottom: 20,
  },
  settingItem: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: 15,
  },
  settingLabel: {
    fontSize: 18,
  },
  settingValue: {
    fontSize: 18,
    color: '#888',
  },
});

export default SettingsScreen;
Enter fullscreen mode Exit fullscreen mode

Notification Preferences Screen

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

const NotificationPreferencesScreen = () => {
  const [orderUpdatesEnabled, setOrderUpdatesEnabled] = useState(true);
  const [promoUpdatesEnabled, setPromoUpdatesEnabled] = useState(true);

  return (
    <View style={styles.container}>
      <Text style={styles.sectionTitle}>Notification Preferences</Text>
      <View style={styles.preferenceItem}>
        <Text style={styles.preferenceLabel}>Order Updates</Text>
        <Switch
          value={orderUpdatesEnabled}
          onValueChange={value => setOrderUpdatesEnabled(value)}
        />
      </View>
      <View style={styles.preferenceItem}>
        <Text style={styles.preferenceLabel}>Promotions</Text>
        <Switch
          value={promoUpdatesEnabled}
          onValueChange={value => setPromoUpdatesEnabled(value)}
        />
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    paddingHorizontal: 20,
    paddingTop: 20,
  },
  sectionTitle: {
    fontSize: 24,
    fontWeight: 'bold',
    marginBottom: 20,
  },
  preferenceItem: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: 15,
  },
  preferenceLabel: {
    fontSize: 18,
  },
});

export default NotificationPreferencesScreen;
Enter fullscreen mode Exit fullscreen mode

Account Settings Screen

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

const AccountSettingsScreen = () => {
  const [fullName, setFullName] = useState('John Doe');
  const [email, setEmail] = useState('johndoe@example.com');
  const [password, setPassword] = useState('');

  const handleSaveChanges = () => {
    // Save changes to backend (simulate here)
    alert('Changes saved successfully!');
  };

  return (
    <View style={styles.container}>
      <Text style={styles.sectionTitle}>Account Settings</Text>
      <Text style={styles.label}>Full Name:</Text>
      <TextInput
        style={styles.input}
        value={fullName}
        onChangeText={setFullName}
      />
      <Text style={styles.label}>Email:</Text>
      <TextInput
        style={styles.input}
        value={email}
        onChangeText={setEmail}
        keyboardType="email-address"
        autoCapitalize="none"
        autoCompleteType="email"
      />
      <Text style={styles.label}>Change Password:</Text>
      <TextInput
        style={styles.input}
        value={password}
        onChangeText={setPassword}
        secureTextEntry
      />
      <Button title="Save Changes" onPress={handleSaveChanges} />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    paddingHorizontal: 20,
    paddingTop: 20,
  },
  sectionTitle: {
    fontSize: 24,
    fontWeight: 'bold',
    marginBottom: 20,
  },
  label: {
    fontSize: 18,
    marginBottom: 5,
  },
  input: {
    width: '100%',
    height: 40,
    borderWidth: 1,
    borderColor: '#ccc',
    paddingHorizontal: 10,
    marginBottom: 15,
  },
});

export default AccountSettingsScreen;
Enter fullscreen mode Exit fullscreen mode

Additional Features

Social Sharing

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

const ProductDetailScreen = ({ product }) => {
  const handleShare = async () => {
    try {
      await Share.share({
        message: `Check out this product: ${product.name} - ${product.description}`,
      });
    } catch (error) {
      alert('Error sharing product');
    }
  };

  return (
    <View style={styles.container}>
      {/* Your product details */}
      <Button title="Share Product" onPress={handleShare} />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    paddingHorizontal: 20,
    paddingTop: 20,
  },
});

export default ProductDetailScreen;
Enter fullscreen mode Exit fullscreen mode

Integration with Customer Support

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

const CustomerSupportScreen = () => {
  const handleChat = () => {
    // Implement live chat integration (open chat URL)
    Linking.openURL('https://example.com/livechat');
  };

  const handleFAQ = () => {
    // Open FAQs screen or link to FAQ page
    Linking.openURL('https://example.com/faqs');
  };

  const handleContactForm = () => {
    // Implement contact form integration (open contact form URL)
    Linking.openURL('https://example.com/contact');
  };

  return (
    <View style={styles.container}>
      <Button title="Live Chat" onPress={handleChat} />
      <Button title="FAQs" onPress={handleFAQ} />
      <Button title="Contact Us" onPress={handleContactForm} />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    paddingHorizontal: 20,
    paddingTop: 20,
  },
});

export default CustomerSupportScreen;
Enter fullscreen mode Exit fullscreen mode

Analytics and Reporting (for admins)

// Example: Implementing analytics screen (admin dashboard)
import React from 'react';
import { View, Text, StyleSheet } from 'react-native';

const AnalyticsScreen = () => {
  // Fetch and display analytics data
  // Implement actual analytics and reporting logic here

  return (
    <View style={styles.container}>
      <Text style={styles.title}>Analytics Dashboard</Text>
      <Text style={styles.text}>Implement your analytics and reporting here.</Text>
      {/* Display charts, graphs, and data */}
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    paddingHorizontal: 20,
    paddingTop: 20,
  },
  title: {
    fontSize: 24,
    fontWeight: 'bold',
    marginBottom: 20,
  },
  text: {
    fontSize: 18,
    marginBottom: 10,
  },
});

export default AnalyticsScreen;
Enter fullscreen mode Exit fullscreen mode

Explanation

  • Settings Screens: These screens handle app-wide settings, notification preferences, and account settings using basic form inputs and toggle switches. They provide a simple implementation to manage user preferences and settings within the app.

  • Additional Features:

    • Social Sharing: Allows users to share product details or app content via native sharing capabilities.
    • Customer Support Integration: Provides buttons to open external links for live chat, FAQs, and contact forms.
    • Analytics and Reporting: Demonstrates a placeholder for an admin dashboard to view analytics and reporting data, which would typically involve more complex data handling and visualization libraries in a real-world application.

These code snippets provide foundational functionality and user interface components for implementing Settings, Social Sharing, Customer Support Integration, and Analytics/Reporting in a React Native ecommerce app. Customize and expand these functionalities based on your specific application requirements and integrate with backend services as needed for data storage and external API interactions.

Implementing an Admin Panel for a React Native app typically involves more complex functionalities and requires backend services to handle data management and authentication securely. Below, I'll provide simplified examples for the Admin Dashboard, Product Management, User Management, and Order Management functionalities using placeholder data and basic UI components.

Admin Dashboard

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

const AdminDashboardScreen = () => {
  // Placeholder data for demonstration
  const totalSales = 5000;
  const totalOrders = 200;
  const pendingOrders = 10;
  const usersCount = 150;

  return (
    <View style={styles.container}>
      <Text style={styles.title}>Admin Dashboard</Text>
      <View style={styles.card}>
        <Text style={styles.cardTitle}>Total Sales</Text>
        <Text style={styles.cardValue}>${totalSales}</Text>
      </View>
      <View style={styles.card}>
        <Text style={styles.cardTitle}>Total Orders</Text>
        <Text style={styles.cardValue}>{totalOrders}</Text>
      </View>
      <View style={styles.card}>
        <Text style={styles.cardTitle}>Pending Orders</Text>
        <Text style={styles.cardValue}>{pendingOrders}</Text>
      </View>
      <View style={styles.card}>
        <Text style={styles.cardTitle}>Total Users</Text>
        <Text style={styles.cardValue}>{usersCount}</Text>
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    paddingHorizontal: 20,
    paddingTop: 20,
  },
  title: {
    fontSize: 24,
    fontWeight: 'bold',
    marginBottom: 20,
  },
  card: {
    backgroundColor: '#f0f0f0',
    padding: 20,
    borderRadius: 8,
    marginBottom: 15,
  },
  cardTitle: {
    fontSize: 18,
    fontWeight: 'bold',
    marginBottom: 5,
  },
  cardValue: {
    fontSize: 24,
  },
});

export default AdminDashboardScreen;
Enter fullscreen mode Exit fullscreen mode

Product Management

import React, { useState, useEffect } from 'react';
import { View, Text, FlatList, Button, StyleSheet } from 'react-native';

const ProductManagementScreen = () => {
  const [products, setProducts] = useState([]);

  useEffect(() => {
    // Fetch products from backend (simulate data for demo)
    const dummyProducts = [
      { id: '1', name: 'Product 1', price: 50 },
      { id: '2', name: 'Product 2', price: 30 },
    ];
    setProducts(dummyProducts);
  }, []);

  const handleDeleteProduct = (productId) => {
    // Implement product deletion logic (simulate here)
    const updatedProducts = products.filter(product => product.id !== productId);
    setProducts(updatedProducts);
  };

  return (
    <View style={styles.container}>
      <Text style={styles.title}>Product Management</Text>
      <FlatList
        data={products}
        keyExtractor={item => item.id}
        renderItem={({ item }) => (
          <View style={styles.productItem}>
            <Text>{item.name}</Text>
            <Text>${item.price}</Text>
            <Button
              title="Delete"
              onPress={() => handleDeleteProduct(item.id)}
            />
          </View>
        )}
      />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    paddingHorizontal: 20,
    paddingTop: 20,
  },
  title: {
    fontSize: 24,
    fontWeight: 'bold',
    marginBottom: 20,
  },
  productItem: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    padding: 10,
    borderWidth: 1,
    borderColor: '#ccc',
    borderRadius: 8,
    marginBottom: 10,
  },
});

export default ProductManagementScreen;
Enter fullscreen mode Exit fullscreen mode

User Management

import React, { useState, useEffect } from 'react';
import { View, Text, FlatList, Button, StyleSheet } from 'react-native';

const UserManagementScreen = () => {
  const [users, setUsers] = useState([]);

  useEffect(() => {
    // Fetch users from backend (simulate data for demo)
    const dummyUsers = [
      { id: '1', name: 'User 1', email: 'user1@example.com' },
      { id: '2', name: 'User 2', email: 'user2@example.com' },
    ];
    setUsers(dummyUsers);
  }, []);

  const handleDeleteUser = (userId) => {
    // Implement user deletion logic (simulate here)
    const updatedUsers = users.filter(user => user.id !== userId);
    setUsers(updatedUsers);
  };

  return (
    <View style={styles.container}>
      <Text style={styles.title}>User Management</Text>
      <FlatList
        data={users}
        keyExtractor={item => item.id}
        renderItem={({ item }) => (
          <View style={styles.userItem}>
            <Text>{item.name}</Text>
            <Text>{item.email}</Text>
            <Button
              title="Delete"
              onPress={() => handleDeleteUser(item.id)}
            />
          </View>
        )}
      />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    paddingHorizontal: 20,
    paddingTop: 20,
  },
  title: {
    fontSize: 24,
    fontWeight: 'bold',
    marginBottom: 20,
  },
  userItem: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    padding: 10,
    borderWidth: 1,
    borderColor: '#ccc',
    borderRadius: 8,
    marginBottom: 10,
  },
});

export default UserManagementScreen;
Enter fullscreen mode Exit fullscreen mode

Order Management

import React, { useState, useEffect } from 'react';
import { View, Text, FlatList, Button, StyleSheet } from 'react-native';

const OrderManagementScreen = () => {
  const [orders, setOrders] = useState([]);

  useEffect(() => {
    // Fetch orders from backend (simulate data for demo)
    const dummyOrders = [
      { id: '1', date: '2023-06-01', total: 100, status: 'Delivered' },
      { id: '2', date: '2023-05-25', total: 150, status: 'Processing' },
    ];
    setOrders(dummyOrders);
  }, []);

  const handleUpdateOrderStatus = (orderId, newStatus) => {
    // Implement order status update logic (simulate here)
    const updatedOrders = orders.map(order => {
      if (order.id === orderId) {
        return { ...order, status: newStatus };
      }
      return order;
    });
    setOrders(updatedOrders);
  };

  return (
    <View style={styles.container}>
      <Text style={styles.title}>Order Management</Text>
      <FlatList
        data={orders}
        keyExtractor={item => item.id}
        renderItem={({ item }) => (
          <View style={styles.orderItem}>
            <Text>Order ID: {item.id}</Text>
            <Text>Date: {item.date}</Text>
            <Text>Total: ${item.total}</Text>
            <Text>Status: {item.status}</Text>
            <Button
              title="Update Status"
              onPress={() => handleUpdateOrderStatus(item.id, 'Shipped')}
            />
          </View>
        )}
      />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    paddingHorizontal: 20,
    paddingTop: 20,
  },
  title: {
    fontSize: 24,
    fontWeight: 'bold',
    marginBottom: 20,
  },
  orderItem: {
    borderWidth: 1,
    borderColor: '#ccc',
    borderRadius: 8,
    padding: 10,
    marginBottom: 10,
  },
});

export default OrderManagementScreen;
Enter fullscreen mode Exit fullscreen mode

Explanation

  • Admin Dashboard: Displays key metrics such as total sales, total orders, pending orders, and total users. This provides a high-level overview of the ecommerce platform's performance.

  • Product Management: Allows admins to view, add, update, and delete products. This includes basic CRUD operations for managing the product catalog.

  • User Management: Provides functionality to view user profiles, edit user details, and handle user-related issues such as support requests or account management.

  • Order Management: Enables admins to view orders, update order statuses (e.g., processing, shipped, delivered), and manage order-related tasks like refunds or cancellations.

These examples serve as a starting point for implementing an Admin Panel in a React Native app. For a production environment, ensure to implement secure authentication, validate inputs, and handle errors gracefully. Additionally, integrate with backend APIs to persist data and manage operations securely.

If you enjoy my content and would like to support my work, you can buy me a coffee. Your support is greatly appreciated!

Disclaimer: This content is generated by AI.

💖 💪 🙅 🚩
nadim_ch0wdhury
Nadim Chowdhury

Posted on June 25, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related