0
0
React Nativemobile~20 mins

File system access in React Native - Mini App: Build & Ship

Choose your learning style9 modes available
Build: File Manager
This screen lets users create, read, and delete a simple text file stored on the device.
Target UI
-------------------------
|      File Manager      |
-------------------------
| Filename: [__________] |
|                       |
| Content:               |
| [                    ] |
| [                    ] |
| [                    ] |
|                       |
| [Save] [Read] [Delete]|
-------------------------
Input field for filename
Multiline input for file content
Save button to write content to file
Read button to load content from file
Delete button to remove the file
Show alert on success or error
Starter Code
React Native
import React, { useState } from 'react';
import { View, TextInput, Button, Alert, StyleSheet, Text } from 'react-native';
import * as FileSystem from 'expo-file-system';

export default function FileManager() {
  const [filename, setFilename] = useState('');
  const [content, setContent] = useState('');

  // TODO: Implement saveFile function

  // TODO: Implement readFile function

  // TODO: Implement deleteFile function

  return (
    <View style={styles.container}>
      <Text style={styles.label}>Filename:</Text>
      <TextInput
        style={styles.input}
        value={filename}
        onChangeText={setFilename}
        placeholder="Enter filename"
        accessibilityLabel="Filename input"
      />
      <Text style={styles.label}>Content:</Text>
      <TextInput
        style={styles.textArea}
        value={content}
        onChangeText={setContent}
        placeholder="Enter file content"
        multiline
        accessibilityLabel="File content input"
      />
      <View style={styles.buttonRow}>
        <Button title="Save" onPress={() => {}} />
        <Button title="Read" onPress={() => {}} />
        <Button title="Delete" onPress={() => {}} />
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, padding: 20, backgroundColor: '#fff' },
  label: { fontSize: 16, marginBottom: 4 },
  input: { borderWidth: 1, borderColor: '#ccc', padding: 8, marginBottom: 12, borderRadius: 4 },
  textArea: { borderWidth: 1, borderColor: '#ccc', padding: 8, height: 100, textAlignVertical: 'top', borderRadius: 4 },
  buttonRow: { flexDirection: 'row', justifyContent: 'space-between', marginTop: 12 }
});
Task 1
Task 2
Task 3
Task 4
Task 5
Solution
React Native
import React, { useState } from 'react';
import { View, TextInput, Button, Alert, StyleSheet, Text } from 'react-native';
import * as FileSystem from 'expo-file-system';

export default function FileManager() {
  const [filename, setFilename] = useState('');
  const [content, setContent] = useState('');

  const getFileUri = () => {
    if (!filename) return null;
    return FileSystem.documentDirectory + filename;
  };

  const saveFile = async () => {
    const fileUri = getFileUri();
    if (!fileUri) {
      Alert.alert('Error', 'Please enter a filename');
      return;
    }
    try {
      await FileSystem.writeAsStringAsync(fileUri, content);
      Alert.alert('Success', 'File saved successfully');
    } catch (e) {
      Alert.alert('Error', 'Failed to save file');
    }
  };

  const readFile = async () => {
    const fileUri = getFileUri();
    if (!fileUri) {
      Alert.alert('Error', 'Please enter a filename');
      return;
    }
    try {
      const fileContent = await FileSystem.readAsStringAsync(fileUri);
      setContent(fileContent);
      Alert.alert('Success', 'File read successfully');
    } catch (e) {
      Alert.alert('Error', 'Failed to read file');
    }
  };

  const deleteFile = async () => {
    const fileUri = getFileUri();
    if (!fileUri) {
      Alert.alert('Error', 'Please enter a filename');
      return;
    }
    try {
      await FileSystem.deleteAsync(fileUri);
      setContent('');
      Alert.alert('Success', 'File deleted successfully');
    } catch (e) {
      Alert.alert('Error', 'Failed to delete file');
    }
  };

  return (
    <View style={styles.container}>
      <Text style={styles.label}>Filename:</Text>
      <TextInput
        style={styles.input}
        value={filename}
        onChangeText={setFilename}
        placeholder="Enter filename"
        accessibilityLabel="Filename input"
      />
      <Text style={styles.label}>Content:</Text>
      <TextInput
        style={styles.textArea}
        value={content}
        onChangeText={setContent}
        placeholder="Enter file content"
        multiline
        accessibilityLabel="File content input"
      />
      <View style={styles.buttonRow}>
        <Button title="Save" onPress={saveFile} />
        <Button title="Read" onPress={readFile} />
        <Button title="Delete" onPress={deleteFile} />
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, padding: 20, backgroundColor: '#fff' },
  label: { fontSize: 16, marginBottom: 4 },
  input: { borderWidth: 1, borderColor: '#ccc', padding: 8, marginBottom: 12, borderRadius: 4 },
  textArea: { borderWidth: 1, borderColor: '#ccc', padding: 8, height: 100, textAlignVertical: 'top', borderRadius: 4 },
  buttonRow: { flexDirection: 'row', justifyContent: 'space-between', marginTop: 12 }
});

We use Expo's FileSystem API to handle file operations in the app's document directory. The getFileUri function builds the full path for the file using the filename input. The saveFile function writes the content to this file path. The readFile function reads the file content and updates the content state to show it in the text area. The deleteFile function removes the file and clears the content. Each function shows an alert to inform the user about success or failure. Buttons are connected to these functions to trigger the actions. Accessibility labels are added for screen readers. The UI uses simple inputs and buttons arranged vertically with spacing.

Final Result
Completed Screen
-------------------------
|      File Manager      |
-------------------------
| Filename: [myfile.txt] |
|                       |
| Content:               |
| [Hello, this is a     ]|
| [sample file content. ]|
| [                    ] |
|                       |
| [Save] [Read] [Delete]|
-------------------------
User types a filename and content.
Tapping Save writes the content to a file and shows a success alert.
Tapping Read loads the file content into the text area and shows a success alert.
Tapping Delete removes the file and clears the content with a success alert.
If filename is empty, alerts prompt user to enter a filename.
Stretch Goal
Add a button to list all files in the document directory and display their names below.
💡 Hint
Use FileSystem.readDirectoryAsync(FileSystem.documentDirectory) to get file list and show it in a scrollable list.