Certainly! Refactoring your Expo mobile app to be more dynamic and modular will enhance maintainability, readability, and scalability. Below is a comprehensive refactored version of your App.js that breaks down functionalities into separate components, utilizes custom hooks for permissions, and ensures dynamic handling of media types.
Overview of Refactoring:
- Modular Components: Separate components for Photo Capture, Video Recording, Voice Recording, and PDF Generation.
- Custom Hooks: Create a custom hook to handle permissions.
- Dynamic Media Handling: Utilize a centralized media state to manage different media types dynamically.
- Enhanced Error Handling: Improved error messages and handling mechanisms.
- Styling: Organized styles for better readability and maintenance.
Refactored Code
1. App.js
// App.js
import React from 'react';
import { StyleSheet, Text, View, ScrollView, Alert } from 'react-native';
import usePermissions from './hooks/usePermissions';
import PhotoCapture from './components/PhotoCapture';
import VideoRecording from './components/VideoRecording';
import VoiceRecording from './components/VoiceRecording';
import PDFGenerator from './components/PDFGenerator';
const App = () => {
const { hasCameraPermission, hasAudioPermission } = usePermissions();
if (hasCameraPermission === null || hasAudioPermission === null) {
return <View style={styles.loadingContainer} />;
}
if (!hasCameraPermission || !hasAudioPermission) {
return (
<View style={styles.permissionContainer}>
<Text style={styles.permissionText}>
No access to camera or microphone. Please enable permissions in your device settings.
</Text>
</View>
);
}
return (
<ScrollView contentContainerStyle={styles.container}>
{/* --- Legal Text Display --- */}
<Text style={styles.header}>Legal Information</Text>
<Text style={styles.legalText}>{legalText}</Text>
{/* --- Photo Capture Section --- */}
<PhotoCapture />
{/* --- Video Recording Section --- */}
<VideoRecording />
{/* --- Voice Recording Section --- */}
<VoiceRecording />
{/* --- PDF Generation Section --- */}
<PDFGenerator />
</ScrollView>
);
};
// --- Legal Text ---
const legalText = `YOUR LEGAL TEXT GOES HERE...
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla vel turpis at quam aliquet lobortis. Integer sit amet ligula vitae justo commodo fermentum. Donec vitae massa a augue blandit porttitor. Proin id purus nec justo mollis finibus sit amet at justo. Mauris ac sem vitae nisl interdum interdum.`;
const styles = StyleSheet.create({
container: {
padding: 20,
paddingBottom: 40,
backgroundColor: '#f5f5f5',
},
loadingContainer: {
flex: 1,
},
permissionContainer: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
permissionText: {
fontSize: 16,
textAlign: 'center',
marginHorizontal: 20,
},
header: {
fontSize: 24,
fontWeight: 'bold',
marginBottom: 10,
},
legalText: {
fontSize: 16,
marginBottom: 20,
lineHeight: 22,
},
});
export default App;
2. hooks/usePermissions.js
Create a custom hook to manage permissions more cleanly.
// hooks/usePermissions.js
import { useState, useEffect } from 'react';
import { Alert } from 'react-native';
import { Camera } from 'expo-camera';
import { Audio } from 'expo-av';
const usePermissions = () => {
const [hasCameraPermission, setHasCameraPermission] = useState(null);
const [hasAudioPermission, setHasAudioPermission] = useState(null);
useEffect(() => {
(async () => {
const cameraStatus = await Camera.requestCameraPermissionsAsync();
setHasCameraPermission(cameraStatus.status === 'granted');
const audioStatus = await Audio.requestPermissionsAsync();
setHasAudioPermission(audioStatus.status === 'granted');
if (
cameraStatus.status !== 'granted' ||
audioStatus.status !== 'granted'
) {
Alert.alert(
'Permissions Required',
'Please grant camera and microphone permissions to use this app.',
[{ text: 'OK' }]
);
}
})();
}, []);
return { hasCameraPermission, hasAudioPermission };
};
export default usePermissions;
3. components/PhotoCapture.js
// components/PhotoCapture.js
import React, { useState, useRef } from 'react';
import { StyleSheet, Text, View, Button, Image, Alert } from 'react-native';
import { Camera } from 'expo-camera';
const PhotoCapture = () => {
const cameraRef = useRef(null);
const [capturedPhoto, setCapturedPhoto] = useState(null);
const takePhoto = async () => {
if (cameraRef.current) {
try {
const photo = await cameraRef.current.takePictureAsync();
setCapturedPhoto(photo.uri);
} catch (error) {
Alert.alert('Error', 'Failed to take photo: ' + error.message);
}
}
};
return (
<View style={styles.section}>
<Text style={styles.subHeader}>Capture Photo</Text>
{!capturedPhoto ? (
<Camera style={styles.camera} ref={cameraRef}>
<View style={styles.buttonContainer}>
<Button title="Take Photo" onPress={takePhoto} />
</View>
</Camera>
) : (
<View style={styles.mediaContainer}>
<Image source={{ uri: capturedPhoto }} style={styles.imagePreview} />
<Button title="Retake Photo" onPress={() => setCapturedPhoto(null)} />
</View>
)}
</View>
);
};
const styles = StyleSheet.create({
section: {
marginBottom: 30,
backgroundColor: '#ffffff',
padding: 15,
borderRadius: 10,
elevation: 2, // For Android
shadowColor: '#000', // For iOS
shadowOffset: { width: 0, height: 2 }, // For iOS
shadowOpacity: 0.25, // For iOS
shadowRadius: 3.84, // For iOS
},
subHeader: {
fontSize: 20,
marginBottom: 10,
fontWeight: '600',
},
camera: {
width: '100%',
height: 250,
borderRadius: 10,
overflow: 'hidden',
},
buttonContainer: {
backgroundColor: 'rgba(0,0,0,0.5)',
padding: 10,
alignItems: 'center',
},
mediaContainer: {
alignItems: 'center',
},
imagePreview: {
width: '100%',
height: 250,
borderRadius: 10,
marginBottom: 10,
resizeMode: 'cover',
},
});
export default PhotoCapture;
4. components/VideoRecording.js
// components/VideoRecording.js
import React, { useState, useRef } from 'react';
import { StyleSheet, Text, View, Button, Alert } from 'react-native';
import { Camera } from 'expo-camera';
import { Video } from 'expo-av';
const VideoRecording = () => {
const videoCameraRef = useRef(null);
const [capturingVideo, setCapturingVideo] = useState(false);
const [capturedVideo, setCapturedVideo] = useState(null);
const startVideoRecording = async () => {
if (videoCameraRef.current) {
try {
setCapturingVideo(true);
const video = await videoCameraRef.current.recordAsync({
maxDuration: 60, // Optional: Set maximum duration (in seconds)
quality: Camera.Constants.VideoQuality['480p'],
});
setCapturedVideo(video.uri);
} catch (error) {
Alert.alert('Error', 'Failed to record video: ' + error.message);
}
}
};
const stopVideoRecording = () => {
if (videoCameraRef.current && capturingVideo) {
videoCameraRef.current.stopRecording();
setCapturingVideo(false);
}
};
return (
<View style={styles.section}>
<Text style={styles.subHeader}>Record Video</Text>
{!capturedVideo ? (
<Camera style={styles.camera} ref={videoCameraRef}>
<View style={styles.buttonContainer}>
{!capturingVideo ? (
<Button title="Start Recording" onPress={startVideoRecording} />
) : (
<Button title="Stop Recording" onPress={stopVideoRecording} color="red" />
)}
</View>
</Camera>
) : (
<View style={styles.mediaContainer}>
<Video
source={{ uri: capturedVideo }}
style={styles.videoPreview}
useNativeControls
resizeMode="contain"
/>
<Button title="Record Again" onPress={() => setCapturedVideo(null)} />
</View>
)}
</View>
);
};
const styles = StyleSheet.create({
section: {
marginBottom: 30,
backgroundColor: '#ffffff',
padding: 15,
borderRadius: 10,
elevation: 2, // For Android
shadowColor: '#000', // For iOS
shadowOffset: { width: 0, height: 2 }, // For iOS
shadowOpacity: 0.25, // For iOS
shadowRadius: 3.84, // For iOS
},
subHeader: {
fontSize: 20,
marginBottom: 10,
fontWeight: '600',
},
camera: {
width: '100%',
height: 250,
borderRadius: 10,
overflow: 'hidden',
},
buttonContainer: {
backgroundColor: 'rgba(0,0,0,0.5)',
padding: 10,
alignItems: 'center',
},
mediaContainer: {
alignItems: 'center',
},
videoPreview: {
width: '100%',
height: 250,
borderRadius: 10,
marginBottom: 10,
},
});
export default VideoRecording;
5. components/VoiceRecording.js
// components/VoiceRecording.js
import React, { useState } from 'react';
import { StyleSheet, Text, View, Button, Alert } from 'react-native';
import { Audio } from 'expo-av';
const VoiceRecording = () => {
const [recording, setRecording] = useState(null);
const [recordedAudioUri, setRecordedAudioUri] = useState(null);
const startVoiceRecording = async () => {
try {
await Audio.setAudioModeAsync({
allowsRecordingIOS: true,
playsInSilentModeIOS: true,
});
const { recording } = await Audio.Recording.createAsync(
Audio.RECORDING_OPTIONS_PRESET_HIGH_QUALITY
);
setRecording(recording);
Alert.alert('Recording Started', 'Speak into your microphone.');
} catch (error) {
Alert.alert('Error', 'Failed to start recording: ' + error.message);
}
};
const stopVoiceRecording = async () => {
try {
await recording.stopAndUnloadAsync();
const uri = recording.getURI();
setRecordedAudioUri(uri);
setRecording(null);
Alert.alert('Recording Stopped', 'Your voice has been recorded.');
} catch (error) {
Alert.alert('Error', 'Failed to stop recording: ' + error.message);
}
};
return (
<View style={styles.section}>
<Text style={styles.subHeader}>Voice Recording</Text>
{!recording ? (
<Button title="Start Recording" onPress={startVoiceRecording} />
) : (
<Button title="Stop Recording" onPress={stopVoiceRecording} color="red" />
)}
{recordedAudioUri && (
<Text style={styles.recordedText}>Audio Recorded: {recordedAudioUri}</Text>
)}
</View>
);
};
const styles = StyleSheet.create({
section: {
marginBottom: 30,
backgroundColor: '#ffffff',
padding: 15,
borderRadius: 10,
elevation: 2, // For Android
shadowColor: '#000', // For iOS
shadowOffset: { width: 0, height: 2 }, // For iOS
shadowOpacity: 0.25, // For iOS
shadowRadius: 3.84, // For iOS
},
subHeader: {
fontSize: 20,
marginBottom: 10,
fontWeight: '600',
},
recordedText: {
marginTop: 10,
fontSize: 14,
color: '#333',
},
});
export default VoiceRecording;
6. components/PDFGenerator.js
// components/PDFGenerator.js
import React, { useState } from 'react';
import { StyleSheet, View, Button, Alert } from 'react-native';
import * as Print from 'expo-print';
import * as Sharing from 'expo-sharing';
import { Image, Video } from 'expo-av';
const PDFGenerator = () => {
const [media, setMedia] = useState({
photo: null,
video: null,
audio: null,
});
// This is a placeholder. In a real application, you would pass the media URIs
// from the respective components (PhotoCapture, VideoRecording, VoiceRecording).
// For example, you might use a Context or a state management library like Redux.
// Here, we'll assume media is being updated elsewhere.
// Example update function (should be replaced with actual data flow)
// setMedia({
// photo: capturedPhotoUri,
// video: capturedVideoUri,
// audio: recordedAudioUri,
// });
const generatePDF = async () => {
// Create HTML content for PDF
let mediaHtml = '';
if (media.photo) {
mediaHtml += `<h2>Captured Photo</h2><img src="${media.photo}" style="width:100%; height:auto;" />`;
}
if (media.video) {
// Note: Embedding video in PDF is not widely supported
mediaHtml += `<h2>Recorded Video</h2>
<p>Video recorded at: <a href="${media.video}">Download Video</a></p>`;
}
if (media.audio) {
// Note: Embedding audio in PDF is not widely supported
mediaHtml += `<h2>Recorded Voice</h2>
<p>Audio recorded at: <a href="${media.audio}">Download Audio</a></p>`;
}
const htmlContent = `
<html>
<head>
<style>
body { font-family: Arial, sans-serif; padding: 20px; }
h1 { text-align: center; }
img { max-width: 100%; height: auto; }
a { color: blue; text-decoration: none; }
</style>
</head>
<body>
<h1>Consent Document</h1>
<p>${legalText}</p>
${mediaHtml}
</body>
</html>
`;
try {
// Generate PDF from HTML
const { uri } = await Print.printToFileAsync({ html: htmlContent });
// Share or download the PDF
await Sharing.shareAsync(uri);
} catch (error) {
Alert.alert('Error', 'Failed to generate PDF: ' + error.message);
}
};
return (
<View style={styles.section}>
<Button title="Download PDF" onPress={generatePDF} />
</View>
);
};
// --- Legal Text (Should be imported or passed as a prop) ---
const legalText = `YOUR LEGAL TEXT GOES HERE...
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla vel turpis at quam aliquet lobortis. Integer sit amet ligula vitae justo commodo fermentum. Donec vitae massa a augue blandit porttitor. Proin id purus nec justo mollis finibus sit amet at justo. Mauris ac sem vitae nisl interdum interdum.`;
const styles = StyleSheet.create({
section: {
marginBottom: 30,
backgroundColor: '#ffffff',
padding: 15,
borderRadius: 10,
elevation: 2, // For Android
shadowColor: '#000', // For iOS
shadowOffset: { width: 0, height: 2 }, // For iOS
shadowOpacity: 0.25, // For iOS
shadowRadius: 3.84, // For iOS
alignItems: 'center',
},
});
export default PDFGenerator;
7. Dynamic Media Handling (Using Context)
To dynamically handle media from different components and make it accessible for PDF generation, we'll use React's Context API.
a. Create context/MediaContext.js
// context/MediaContext.js
import React, { createContext, useState } from 'react';
export const MediaContext = createContext();
export const MediaProvider = ({ children }) => {
const [media, setMedia] = useState({
photo: null,
video: null,
audio: null,
});
const updateMedia = (type, uri) => {
setMedia((prevMedia) => ({
...prevMedia,
[type]: uri,
}));
};
return (
<MediaContext.Provider value={{ media, updateMedia }}>
{children}
</MediaContext.Provider>
);
};
b. Update App.js to include MediaProvider
// App.js (Updated)
import React from 'react';
import { StyleSheet, Text, View, ScrollView, Alert } from 'react-native';
import usePermissions from './hooks/usePermissions';
import PhotoCapture from './components/PhotoCapture';
import VideoRecording from './components/VideoRecording';
import VoiceRecording from './components/VoiceRecording';
import PDFGenerator from './components/PDFGenerator';
import { MediaProvider } from './context/MediaContext';
const App = () => {
const { hasCameraPermission, hasAudioPermission } = usePermissions();
if (hasCameraPermission === null || hasAudioPermission === null) {
return <View style={styles.loadingContainer} />;
}
if (!hasCameraPermission || !hasAudioPermission) {
return (
<View style={styles.permissionContainer}>
<Text style={styles.permissionText}>
No access to camera or microphone. Please enable permissions in your device settings.
</Text>
</View>
);
}
return (
<MediaProvider>
<ScrollView contentContainerStyle={styles.container}>
{/* --- Legal Text Display --- */}
<Text style={styles.header}>Legal Information</Text>
<Text style={styles.legalText}>{legalText}</Text>
{/* --- Photo Capture Section --- */}
<PhotoCapture />
{/* --- Video Recording Section --- */}
<VideoRecording />
{/* --- Voice Recording Section --- */}
<VoiceRecording />
{/* --- PDF Generation Section --- */}
<PDFGenerator />
</ScrollView>
</MediaProvider>
);
};
// --- Legal Text ---
const legalText = `YOUR LEGAL TEXT GOES HERE...
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla vel turpis at quam aliquet lobortis. Integer sit amet ligula vitae justo commodo fermentum. Donec vitae massa a augue blandit porttitor. Proin id purus nec justo mollis finibus sit amet at justo. Mauris ac sem vitae nisl interdum interdum.`;
const styles = StyleSheet.create({
container: {
padding: 20,
paddingBottom: 40,
backgroundColor: '#f5f5f5',
},
loadingContainer: {
flex: 1,
},
permissionContainer: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
permissionText: {
fontSize: 16,
textAlign: 'center',
marginHorizontal: 20,
},
header: {
fontSize: 24,
fontWeight: 'bold',
marginBottom: 10,
},
legalText: {
fontSize: 16,
marginBottom: 20,
lineHeight: 22,
},
});
export default App;
c. Update Components to Use MediaContext
Example for PhotoCapture.js:
// components/PhotoCapture.js (Updated)
import React, { useState, useRef, useContext } from 'react';
import { StyleSheet, Text, View, Button, Image, Alert } from 'react-native';
import { Camera } from 'expo-camera';
import { MediaContext } from '../context/MediaContext';
const PhotoCapture = () => {
const cameraRef = useRef(null);
const { media, updateMedia } = useContext(MediaContext);
const [capturedPhoto, setCapturedPhoto] = useState(media.photo);
const takePhoto = async () => {
if (cameraRef.current) {
try {
const photo = await cameraRef.current.takePictureAsync();
setCapturedPhoto(photo.uri);
updateMedia('photo', photo.uri);
} catch (error) {
Alert.alert('Error', 'Failed to take photo: ' + error.message);
}
}
};
return (
<View style={styles.section}>
<Text style={styles.subHeader}>Capture Photo</Text>
{!capturedPhoto ? (
<Camera style={styles.camera} ref={cameraRef}>
<View style={styles.buttonContainer}>
<Button title="Take Photo" onPress={takePhoto} />
</View>
</Camera>
) : (
<View style={styles.mediaContainer}>
<Image source={{ uri: capturedPhoto }} style={styles.imagePreview} />
<Button title="Retake Photo" onPress={() => { setCapturedPhoto(null); updateMedia('photo', null); }} />
</View>
)}
</View>
);
};
// ... (styles remain the same)
export default PhotoCapture;
Similarly, update VideoRecording.js and VoiceRecording.js to use MediaContext.
VideoRecording.js Updated:
// components/VideoRecording.js (Updated)
import React, { useState, useRef, useContext } from 'react';
import { StyleSheet, Text, View, Button, Alert } from 'react-native';
import { Camera } from 'expo-camera';
import { Video } from 'expo-av';
import { MediaContext } from '../context/MediaContext';
const VideoRecording = () => {
const videoCameraRef = useRef(null);
const { media, updateMedia } = useContext(MediaContext);
const [capturingVideo, setCapturingVideo] = useState(false);
const [capturedVideo, setCapturedVideo] = useState(media.video);
const startVideoRecording = async () => {
if (videoCameraRef.current) {
try {
setCapturingVideo(true);
const video = await videoCameraRef.current.recordAsync({
maxDuration: 60,
quality: Camera.Constants.VideoQuality['480p'],
});
setCapturedVideo(video.uri);
updateMedia('video', video.uri);
} catch (error) {
Alert.alert('Error', 'Failed to record video: ' + error.message);
}
}
};
const stopVideoRecording = () => {
if (videoCameraRef.current && capturingVideo) {
videoCameraRef.current.stopRecording();
setCapturingVideo(false);
}
};
return (
<View style={styles.section}>
<Text style={styles.subHeader}>Record Video</Text>
{!capturedVideo ? (
<Camera style={styles.camera} ref={videoCameraRef}>
<View style={styles.buttonContainer}>
{!capturingVideo ? (
<Button title="Start Recording" onPress={startVideoRecording} />
) : (
<Button title="Stop Recording" onPress={stopVideoRecording} color="red" />
)}
</View>
</Camera>
) : (
<View style={styles.mediaContainer}>
<Video
source={{ uri: capturedVideo }}
style={styles.videoPreview}
useNativeControls
resizeMode="contain"
/>
<Button title="Record Again" onPress={() => { setCapturedVideo(null); updateMedia('video', null); }} />
</View>
)}
</View>
);
};
// ... (styles remain the same)
export default VideoRecording;
VoiceRecording.js Updated:
// components/VoiceRecording.js (Updated)
import React, { useState, useContext } from 'react';
import { StyleSheet, Text, View, Button, Alert } from 'react-native';
import { Audio } from 'expo-av';
import { MediaContext } from '../context/MediaContext';
const VoiceRecording = () => {
const { media, updateMedia } = useContext(MediaContext);
const [recording, setRecording] = useState(null);
const [recordedAudioUri, setRecordedAudioUri] = useState(media.audio);
const startVoiceRecording = async () => {
try {
await Audio.setAudioModeAsync({
allowsRecordingIOS: true,
playsInSilentModeIOS: true,
});
const { recording } = await Audio.Recording.createAsync(
Audio.RECORDING_OPTIONS_PRESET_HIGH_QUALITY
);
setRecording(recording);
Alert.alert('Recording Started', 'Speak into your microphone.');
} catch (error) {
Alert.alert('Error', 'Failed to start recording: ' + error.message);
}
};
const stopVoiceRecording = async () => {
try {
await recording.stopAndUnloadAsync();
const uri = recording.getURI();
setRecordedAudioUri(uri);
updateMedia('audio', uri);
setRecording(null);
Alert.alert('Recording Stopped', 'Your voice has been recorded.');
} catch (error) {
Alert.alert('Error', 'Failed to stop recording: ' + error.message);
}
};
return (
<View style={styles.section}>
<Text style={styles.subHeader}>Voice Recording</Text>
{!recording ? (
<Button title="Start Recording" onPress={startVoiceRecording} />
) : (
<Button title="Stop Recording" onPress={stopVoiceRecording} color="red" />
)}
{recordedAudioUri && (
<Text style={styles.recordedText}>Audio Recorded: {recordedAudioUri}</Text>
)}
</View>
);
};
const styles = StyleSheet.create({
section: {
marginBottom: 30,
backgroundColor: '#ffffff',
padding: 15,
borderRadius: 10,
elevation: 2, // For Android
shadowColor: '#000', // For iOS
shadowOffset: { width: 0, height: 2 }, // For iOS
shadowOpacity: 0.25, // For iOS
shadowRadius: 3.84, // For iOS
},
subHeader: {
fontSize: 20,
marginBottom: 10,
fontWeight: '600',
},
recordedText: {
marginTop: 10,
fontSize: 14,
color: '#333',
},
});
export default VoiceRecording;
d. Update PDFGenerator.js to Use MediaContext
// components/PDFGenerator.js (Updated)
import React, { useContext } from 'react';
import { StyleSheet, View, Button, Alert } from 'react-native';
import * as Print from 'expo-print';
import * as Sharing from 'expo-sharing';
import { MediaContext } from '../context/MediaContext';
const PDFGenerator = () => {
const { media } = useContext(MediaContext);
const generatePDF = async () => {
// Create HTML content for PDF
let mediaHtml = '';
if (media.photo) {
mediaHtml += `<h2>Captured Photo</h2><img src="${media.photo}" style="width:100%; height:auto;" />`;
}
if (media.video) {
// Note: Embedding video in PDF is not widely supported
mediaHtml += `<h2>Recorded Video</h2>
<p>Video recorded at: <a href="${media.video}">Download Video</a></p>`;
}
if (media.audio) {
// Note: Embedding audio in PDF is not widely supported
mediaHtml += `<h2>Recorded Voice</h2>
<p>Audio recorded at: <a href="${media.audio}">Download Audio</a></p>`;
}
const htmlContent = `
<html>
<head>
<style>
body { font-family: Arial, sans-serif; padding: 20px; }
h1 { text-align: center; }
img { max-width: 100%; height: auto; }
a { color: blue; text-decoration: none; }
</style>
</head>
<body>
<h1>Consent Document</h1>
<p>${legalText}</p>
${mediaHtml}
</body>
</html>
`;
try {
// Generate PDF from HTML
const { uri } = await Print.printToFileAsync({ html: htmlContent });
// Share or download the PDF
await Sharing.shareAsync(uri);
} catch (error) {
Alert.alert('Error', 'Failed to generate PDF: ' + error.message);
}
};
return (
<View style={styles.section}>
<Button title="Download PDF" onPress={generatePDF} />
</View>
);
};
// --- Legal Text (Should be imported or passed as a prop) ---
const legalText = `YOUR LEGAL TEXT GOES HERE...
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla vel turpis at quam aliquet lobortis. Integer sit amet ligula vitae justo commodo fermentum. Donec vitae massa a augue blandit porttitor. Proin id purus nec justo mollis finibus sit amet at justo. Mauris ac sem vitae nisl interdum interdum.`;
const styles = StyleSheet.create({
section: {
marginBottom: 30,
backgroundColor: '#ffffff',
padding: 15,
borderRadius: 10,
elevation: 2, // For Android
shadowColor: '#000', // For iOS
shadowOffset: { width: 0, height: 2 }, // For iOS
shadowOpacity: 0.25, // For iOS
shadowRadius: 3.84, // For iOS
alignItems: 'center',
},
});
export default PDFGenerator;
Benefits of This Refactoring:
- Modularity: Each functionality is encapsulated within its own component, making the codebase easier to navigate and maintain.
- Reusability: Components can be reused in different parts of the application or even in other projects.
- State Management: Using React Context (
MediaContext) allows centralized management of media states, making data flow more predictable.
- Custom Hooks: The
usePermissions hook abstracts permission logic, keeping components clean.
- Scalability: Adding new features or media types becomes straightforward with the current structure.
- Dynamic Handling: Media content is handled dynamically through context, ensuring that the PDF generation reflects the current state accurately.
Additional Recommendations:
- Error Boundary: Consider adding an error boundary to catch and handle unexpected errors gracefully.
- Type Checking: Utilize TypeScript or PropTypes for type checking to prevent type-related bugs.
- UI Enhancements: Enhance the UI/UX with better styling, loading indicators, and feedback mechanisms.
- Testing: Implement unit and integration tests to ensure each component behaves as expected.
- Performance Optimization: Optimize media handling to manage memory usage, especially when dealing with large files.
By implementing this refactored structure, your Expo mobile app will not only be more dynamic but also more robust and maintainable for future developments.