Exercise 1 : Forms and Validation
import DateTimePicker from "@react-native-community/datetimepicker";
import Checkbox from "expo-checkbox";
import React, { useState } from "react";
import { View, TextInput, Text, Switch, Button, Alert, StyleSheet } from "react-native";
export default function App() {
const [name, setName] = useState("");
const [dateOfBirth, setDateOfBirth] = useState(new Date());
const [numberOfPets, setNumberOfPets] = useState("");
const [isDeveloper, setIsDeveloper] = useState(false);
const [isAgreed, setIsAgreed] = useState(false);
const [age, setAge] = useState("");
const handleNameChange = (text) => {
setName(text);
};
const handleDateOfBirthChange = (event, selectedDate) => {
const currentDate = selectedDate || dateOfBirth;
setDateOfBirth(currentDate);
calculateAge(currentDate);
};
const handleNumberOfPetsChange = (text) => {
setNumberOfPets(text);
};
const handleDeveloperSwitchChange = (value) => {
setIsDeveloper(value);
};
const handleAgreedCheckboxChange = (value) => {
setIsAgreed(value);
};
const calculateAge = (birthDate) => {
const today = new Date();
const diff = today - birthDate;
const age = Math.floor(diff / (1000 * 60 * 60 * 24 * 365.25));
setAge(age.toString());
};
const handleSubmit = () => {
if (!name || name.length < 3) {
Alert.alert("Error", "Name should contain at least 3 characters");
return;
}
if (dateOfBirth > new Date()) {
Alert.alert("Error", "Date of Birth cannot be a future date");
return;
}
if (!isAgreed) {
Alert.alert("Error", "You must agree to the rules before submitting");
return;
}
// If all validations pass, display the form information
const message = `Name: ${name}\nDate of Birth: ${dateOfBirth.toDateString()}\nAge: ${age}\nNumber of Pets: ${numberOfPets}\nReact Native Developer: ${
isDeveloper ? "Yes" : "No"
}`;
Alert.alert("Form Submitted", message);
};
return (
<View style={styles.container}>
<TextInput
style={styles.input}
placeholder="Name"
onChangeText={handleNameChange}
value={name}
maxLength={30}
/>
<DateTimePicker
value={dateOfBirth}
mode="date"
onChange={handleDateOfBirthChange}
maximumDate={new Date()}
/>
<TextInput
style={styles.input}
placeholder="Number of Pets"
onChangeText={handleNumberOfPetsChange}
value={numberOfPets}
keyboardType="numeric"
maxLength={2}
/>
<View style={styles.switchContainer}>
<Switch value={isDeveloper} onValueChange={handleDeveloperSwitchChange} />
<Text style={styles.switchText}>I'm a great React Native developer</Text>
</View>
<View style={styles.switchContainer}>
<Checkbox value={isAgreed} onValueChange={handleAgreedCheckboxChange} />
<Text style={styles.switchText}>
I understand the rules of the project and I'll do my best
</Text>
</View>
<Button title="Submit" onPress={handleSubmit} disabled={!name || !dateOfBirth || !isAgreed} />
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: "center",
justifyContent: "center",
paddingHorizontal: 20,
},
input: {
width: "100%",
height: 40,
borderWidth: 1,
borderColor: "#ccc",
borderRadius: 5,
marginBottom: 10,
paddingHorizontal: 10,
},
switchContainer: {
flexDirection: "row",
alignItems: "center",
marginBottom: 10,
},
switchText: {
marginLeft: 10,
},
});
Exercise 2
To implement navigation and context to pass data between screens in a React Native application, you'll need to use React Navigation and React's Context API.
First, let's create a context to store the form data:
import React from 'react';
export const FormDataContext = React.createContext();
Next, in your main App.js file, you'll need to set up navigation and provide the context to your screens:
import React, { useState } from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import { FormDataContext } from './FormDataContext';
import FormScreen from './FormScreen';
import DetailsScreen from './DetailsScreen';
const Stack = createStackNavigator();
export default function App() {
const [formData, setFormData] = useState(null);
return (
<FormDataContext.Provider value={{ formData, setFormData }}>
<NavigationContainer>
<Stack.Navigator initialRouteName="Form">
<Stack.Screen name="Form" component={FormScreen} />
<Stack.Screen name="Details" component={DetailsScreen} />
</Stack.Navigator>
</NavigationContainer>
</FormDataContext.Provider>
);
}
Now, you can update your FormScreen component to navigate to the DetailsScreen upon submission, and to update the context with the form data:
import React, { useContext } from 'react';
import { FormDataContext } from './FormDataContext';
// ...rest of your imports
const FormScreen = ({ navigation }) => {
const { setFormData } = useContext(FormDataContext);
// ...rest of your code
const onSubmit = () => {
const data = {
name,
dob,
age: calculateAge(dob),
numPets,
isGreatDeveloper,
understandRules,
};
setFormData(data);
navigation.navigate('Details');
};
// ...rest of your code
};
Finally, in your DetailsScreen, you can display the form data:
import React, { useContext } from 'react';
import { View, Text } from 'react-native';
import { FormDataContext } from './FormDataContext';
const DetailsScreen = () => {
const { formData } = useContext(FormDataContext);
return (
<View>
<Text>Name: {formData.name}</Text>
<Text>Date of Birth: {formData.dob.toString()}</Text>
<Text>Age: {formData.age}</Text>
<Text>Number of Pets: {formData.numPets}</Text>
<Text>Is a great React Native developer: {formData.isGreatDeveloper ? 'Yes' : 'No'}</Text>
<Text>Understands the rules: {formData.understandRules ? 'Yes' : 'No'}</Text>
</View>
);
};
export default DetailsScreen;
With this, you have successfully created a DetailsScreen where you display the user's form input. This input is passed between screens using React's Context API. The FormScreen navigates to the DetailsScreen upon form submission, and the DetailsScreen retrieves the form data from the context and displays it.
Please remember to import the FormDataContext in every file where you plan to use it. Also, replace './FormDataContext', './FormScreen', and './DetailsScreen' with the actual paths to these files in your project.