RN

React Native Integration

Complete guide for integrating Calligraphy API in React Native apps

iOS & AndroidProduction ReadyTypeScript Support
Quick Start

1. Install Dependencies

bash
Click to copy
# Install HTTP client
npm install axios
# OR
npm install fetch

# For image handling (optional)
npm install react-native-fs
npm install react-native-share

2. Basic Implementation

javascript
Click to copy
import React, { useState } from 'react';
import {
  View,
  Text,
  TextInput,
  TouchableOpacity,
  Image,
  Alert,
  StyleSheet,
  ActivityIndicator,
} from 'react-native';
import axios from 'axios';

const CalligraphyGenerator = () => {
  const [text, setText] = useState('नमस्ते दुनिया');
  const [imageUrl, setImageUrl] = useState(null);
  const [loading, setLoading] = useState(false);

  const generateCalligraphy = async () => {
    setLoading(true);
    
    try {
      const response = await axios.post(
        'https://api.calligraphymaker.com/api/v2/generate',
        {
          text: text,
          language: 'hindi',
          fontStyle: 'calligraphy',
          count: 1,
          imageFormat: 'png'
        },
        {
          headers: {
            'Content-Type': 'application/json',
            'x-api-key': 'YOUR_API_KEY_HERE'
          }
        }
      );

      if (response.data.success && response.data.data.results.length > 0) {
        setImageUrl(response.data.data.results[0].cdnUrl);
      } else {
        Alert.alert('Error', 'Failed to generate calligraphy');
      }
    } catch (error) {
      console.error('Error generating calligraphy:', error);
      Alert.alert('Error', 'Network error occurred');
    } finally {
      setLoading(false);
    }
  };

  return (
    <View style={styles.container}>
      <Text style={styles.title}>Calligraphy Generator</Text>
      
      <TextInput
        style={styles.input}
        value={text}
        onChangeText={setText}
        placeholder="Enter text to convert"
        multiline
      />
      
      <TouchableOpacity
        style={styles.button}
        onPress={generateCalligraphy}
        disabled={loading}
      >
        {loading ? (
          <ActivityIndicator color="#fff" />
        ) : (
          <Text style={styles.buttonText}>Generate Calligraphy</Text>
        )}
      </TouchableOpacity>
      
      {imageUrl && (
        <View style={styles.imageContainer}>
          <Image
            source={{ uri: imageUrl }}
            style={styles.image}
            resizeMode="contain"
          />
        </View>
      )}
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 20,
    backgroundColor: '#f5f5f5',
  },
  title: {
    fontSize: 24,
    fontWeight: 'bold',
    textAlign: 'center',
    marginBottom: 20,
    color: '#333',
  },
  input: {
    backgroundColor: '#fff',
    borderRadius: 8,
    padding: 15,
    marginBottom: 20,
    fontSize: 16,
    borderWidth: 1,
    borderColor: '#ddd',
    minHeight: 80,
  },
  button: {
    backgroundColor: '#2563eb',
    borderRadius: 8,
    padding: 15,
    alignItems: 'center',
    marginBottom: 20,
  },
  buttonText: {
    color: '#fff',
    fontSize: 16,
    fontWeight: 'bold',
  },
  imageContainer: {
    backgroundColor: '#fff',
    borderRadius: 8,
    padding: 20,
    alignItems: 'center',
  },
  image: {
    width: '100%',
    height: 200,
  },
});

export default CalligraphyGenerator;
Advanced Features

Custom Hook for API Integration

javascript
Click to copy
// hooks/useCalligraphyAPI.js
import { useState, useCallback } from 'react';
import axios from 'axios';

const API_BASE_URL = 'https://api.calligraphymaker.com/api/v2';
const API_KEY = 'YOUR_API_KEY_HERE';

export const useCalligraphyAPI = () => {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  const generateCalligraphy = useCallback(async (options) => {
    setLoading(true);
    setError(null);

    try {
      const response = await axios.post(
        `${API_BASE_URL}/generate`,
        {
          text: options.text,
          language: options.language || 'hindi',
          fontStyle: options.fontStyle || 'calligraphy',
          count: options.count || 1,
          imageFormat: options.imageFormat || 'png'
        },
        {
          headers: {
            'Content-Type': 'application/json',
            'x-api-key': API_KEY
          }
        }
      );

      return response.data;
    } catch (err) {
      const errorMessage = err.response?.data?.error || 'Network error occurred';
      setError(errorMessage);
      throw new Error(errorMessage);
    } finally {
      setLoading(false);
    }
  }, []);

  const downloadSVG = useCallback(async (resultText, fontName) => {
    setLoading(true);
    setError(null);

    try {
      const response = await axios.post(
        `${API_BASE_URL}/download-svg`,
        {
          resultText,
          fontName
        },
        {
          headers: {
            'Content-Type': 'application/json',
            'x-api-key': API_KEY
          }
        }
      );

      return response.data;
    } catch (err) {
      const errorMessage = err.response?.data?.error || 'Network error occurred';
      setError(errorMessage);
      throw new Error(errorMessage);
    } finally {
      setLoading(false);
    }
  }, []);

  return {
    generateCalligraphy,
    downloadSVG,
    loading,
    error
  };
};

File Download & Sharing

javascript
Click to copy
import RNFS from 'react-native-fs';
import Share from 'react-native-share';

const downloadAndShareImage = async (imageUrl, filename = 'calligraphy.png') => {
  try {
    // Download image to local storage
    const downloadPath = `${RNFS.DocumentDirectoryPath}/${filename}`;
    
    const downloadResult = await RNFS.downloadFile({
      fromUrl: imageUrl,
      toFile: downloadPath,
    }).promise;

    if (downloadResult.statusCode === 200) {
      // Share the downloaded file
      const shareOptions = {
        title: 'Beautiful Calligraphy',
        message: 'Check out this beautiful calligraphy!',
        url: `file://${downloadPath}`,
        type: 'image/png',
      };

      await Share.open(shareOptions);
      return downloadPath;
    } else {
      throw new Error('Download failed');
    }
  } catch (error) {
    console.error('Error downloading/sharing image:', error);
    throw error;
  }
};

// Usage in component
const handleDownloadAndShare = async () => {
  if (imageUrl) {
    try {
      await downloadAndShareImage(imageUrl);
      Alert.alert('Success', 'Image downloaded and shared!');
    } catch (error) {
      Alert.alert('Error', 'Failed to download image');
    }
  }
};
Error Handling
javascript
Click to copy
// utils/errorHandler.js
export const handleAPIError = (error) => {
  if (error.response) {
    // Server responded with error status
    const { status, data } = error.response;
    
    switch (status) {
      case 401:
        return 'Invalid API key. Please check your credentials.';
      case 402:
        return 'Insufficient credits. Please upgrade your plan.';
      case 429:
        return 'Rate limit exceeded. Please try again later.';
      case 400:
        return data.error || 'Invalid request parameters.';
      default:
        return data.error || 'Server error occurred.';
    }
  } else if (error.request) {
    // Network error
    return 'Network error. Please check your internet connection.';
  } else {
    // Other error
    return error.message || 'An unexpected error occurred.';
  }
};

// Enhanced component with error handling
const CalligraphyGeneratorEnhanced = () => {
  const { generateCalligraphy, loading, error } = useCalligraphyAPI();
  const [results, setResults] = useState([]);

  const handleGenerate = async () => {
    try {
      const response = await generateCalligraphy({
        text: inputText,
        language: selectedLanguage,
        fontStyle: selectedStyle,
        count: 3
      });

      if (response.success) {
        setResults(response.data.results);
      }
    } catch (err) {
      const errorMessage = handleAPIError(err);
      Alert.alert('Error', errorMessage);
    }
  };

  return (
    <View style={styles.container}>
      {error && (
        <View style={styles.errorContainer}>
          <Text style={styles.errorText}>{error}</Text>
        </View>
      )}
      
      {/* Rest of component */}
    </View>
  );
};
What You'll Build
Cross-platform App
Works on both iOS and Android
Real-time Generation
Generate calligraphy as users type
Download & Share
Save and share generated images
Error Handling
Graceful error management
Requirements
React Native 0.60+
Node.js 14+
API Key from Calligraphy API
iOS/Android development setup