Skip to main content

· 4 min read
Youcef

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.

· 2 min read
Youcef

Setup​

  1. Create a new Expo project
  2. Install eslint and prettier
  3. Run the app on your phone
  4. Try to run your app on a simulator

Exercise 1 : Forms and Validation​

Objective: To understand and implement forms with validation in React Native with Expo. You'll be creating a form with several fields and their respective validations.

Create a form with the following fields:

  • Name - Text input (required, should contain only characters, with a minimum of 3 characters)
  • Date of Birth - Date picker (required, should not be a future date) - You can use @react-native-community/datetimepicker
  • Age - This field should be automatically calculated based on the Date of Birth input - Should be a disabled input
  • Number of Pets - A number input field (should contain only digits) - Optional
  • I'm a great React Native developer (Yes/No) - Implement this using a Switch component
  • I understand the rules of the project and I'll do my best - Implement this using a Checkbox component expo-checkbox - This should be checked before the form can be submitted

Add a button at the bottom of the screen. The button should be disabled if the required information is not provided.

On submit, the info should be displayed through an Alert component.

Exercise 2 : Context​

Create a new screen called DetailsScreen. On submit of the form, you should navigate to this new screen and, without passing route parameters, display the info of the form.

Exercise 3 : useReducer​

Refactor your code using useReducer as seen in the course https://react.dev/learn/scaling-up-with-reducer-and-context

· 12 min read
Youcef

We're going to be building a Calories Counter and Meal Planner application using React Native and Expo. This application will allow users to set their health goals, choose items from a food database to track caloric intake, and plan meals accordingly. As we work through this project, we'll be learning and applying key concepts we saw during the course, including user input handling, API integration, state management, and UI styling. Let's dive right in.

Rules​

Each item is mandatory

  • Teams of 2 students
  • Use React Native AND Expo
  • The two students have to commit to the project repository
  • The use of GPT is prohibited and punishable by a 0/20

Module 1: Setting up the project​

Our first step in this journey is to set up our development environment and initiate our project. Here are the steps to follow:

  • Step 1: Create a New Expo Project
  • Step 2: Install eslint and prettier
  • Step 3: Install React Navigation
  • Step 4: Run the app on your phone using Expo Go

After this we will create 3 tabs using a Bottom Tab Navigator

  • Tab 1: Health goals
  • Tab 2: Food database
  • Tab 3: Meal planning

Module 2 : Health goals​

In this module, we will be implementing the functionality for users to set their health goals and receive a daily caloric intake suggestion based on these goals. The main objective of this module is to understand how to capture user inputs, handle state management in React Native, and apply basic mathematical models in software applications.

Here's a step-by-step breakdown:

Step 1: Creating a Form for User Input​

Firstly, we need to create a form where users can input their personal details and health goals. The form should include fields for:

  • Age
  • Gender
  • Height
  • Weight
  • Activity level (with options like sedentary, light exercise, moderate exercise, heavy exercise, extra active)
  • Health goal (with options like weight loss, weight maintenance, weight gain)

You can use the TextInput and Picker components from React Native for this.

Step 2: Handling User Input​

Once the form is set up, we need to handle user input. This involves setting up state variables for each input field using the useState hook and updating these variables as the user enters their data. Also, you should add proper form validation (disable the button one of the fields is empty for example).

Step 3: Calculating BMR Using the Harris-Benedict Equation​

The next step is to calculate the user's Basal Metabolic Rate (BMR) using the Harris-Benedict equation. The equation is different for men and women:

For men: BMR = 88.362 + (13.397 * weight in kg) + (4.799 * height in cm) - (5.677 * age in years)

For women: BMR = 447.593 + (9.247 * weight in kg) + (3.098 * height in cm) - (4.330 * age in years)

We will need to create a function that takes the user's age, gender, height, and weight as input, and returns the BMR as output.

Step 4: Adjusting BMR Based on Activity Level​

The BMR needs to be adjusted based on the user's activity level to get the total amount of calories they need to maintain their current weight. The adjustment factors are as follows:

  • Sedentary (little or no exercise): BMR * 1.2
  • Lightly active (light exercise/sports 1-3 days/week): BMR * 1.375
  • Moderately active (moderate exercise/sports 3-5 days/week): BMR * 1.55
  • Very active (hard exercise/sports 6-7 days a week): BMR * 1.725
  • Super active (very hard exercise/physical job & exercise 2x/day): BMR * 1.9

We need to add this calculation to the function created in the previous step.

Step 5: Adjusting Caloric Intake Based on Health Goal​

Finally, the total caloric intake needs to be adjusted based on the user's health goal. If the user wants to lose weight, subtract 10% calories from the total. If the user wants to gain weight, add 10% calories to the total. If the user wants to maintain weight, the total caloric intake remains the same.

Step 6: Displaying the Result to the User​

Once the daily caloric intake has been calculated, it should be displayed to the user. we can create a new component to display the result, or they can display it in an existing component.

Absolutely! Welcome back, students. We've made great progress on our Calories Counter and Meal Planner application, having already set up our project and implemented the functionality for users to set their health goals. Now, it's time to move on to the next part of our application: the Food Database.

Module 3: Food Database​

In this module, we're going to a feature where users can search for foods and see their nutritional information. This will involve integrating with a nutrition API to get this information, and creating a user interface where users can search for foods and view their details. Let's dive into the steps.

Step 1: Choosing a Nutrition API

There are several nutrition APIs available that provide detailed information about different foods, including their calorie content and other nutritional facts. Some examples include these: https://developer.edamam.com/food-database-api or https://www.nutritionix.com/business/api. You'll need to choose one of these APIs (or another of your choice), sign up to get an API key, and familiarize yourself with the API documentation to understand how to make requests.

Step 2: Creating the Search Interface

Next, you'll create a new screen in your application for the food database. This screen should include a search bar where users can enter the name of a food. You can use the TextInput component from React Native for this.

Step 3: Handling User Input

Set up a state variable for the search query and update this variable as the user types into the search bar. You can do this using the useState and onChangeText props. Add a submit button to launch the search.

Step 4: Fetching Data from the API

When the user submits their search, make a request to the nutrition API to get information about the food. You'll need to refer to your chosen API's documentation to know exactly how to structure this request, but typically it will involve sending a GET request to a specific endpoint, with the search query and your API key included as parameters.

Step 5: Displaying the Results

Once you receive the response from the API, extract the relevant information and display it to the user. This could include the food's name, calorie content, and other nutritional facts. Ensure to handle any errors that might occur, such as the food not being found in the database.

Step 6: Selecting Food for Meal Planning

After displaying the search results, allow the user to select a food item to add to their meal plan. You will need to create some form of selection interface – this could be as simple as the reult item being a TouchableOpacity with a Text.

When a food item is selected, prompt the user to specify the quantity the day AND which meal this food item should be added to (Breakfast, Lunch, Dinner, or Snack). You can create a modal or a new screen to handle this. Use the Picker component from React Native for the meal type selection.

Step 7: Updating the Meal Plan

Upon the user's confirmation, update the user's meal plan with the chosen food item. The meal plan could be an object in your application's state that stores an array of food items for each day and each meal type. Here is an example structure:

{
"Day": {
"Breakfast": [],
"Lunch": [],
"Snack": [],
"Dinner": []
}
}

Each time a food item is added, push it to the appropriate array in this object.

Module 4: Meal Planning​

In this module, we'll develop the core feature of our application: the Meal Planner. This will allow users to plan their meals for the week and view a summary of the planned meals along with the total calories for each day. Let's get started!

Step 1: Creating the Meal Planner Interface

First, create a new screen in your application for the Meal Planner. This screen should include a view for each day of the week, and within each day, a section for each meal (Breakfast, Lunch, Dinner, Snack). You may use the View and Text components from React Native for this purpose.

Step 2: Displaying the Meal Plan

Next, you'll need to display the user's meal plan in the Meal Planner screen.

For each day and each meal, list out the food items that the user has added to their meal plan. You might want to create a separate component for each meal that takes the array of food items as a prop and renders them in a list.

Step 3: Calculating Daily Calories

For each day, calculate the total calories of all food items in the meal plan. This can be done by looping through the food items for each meal, summing up their calorie content, and displaying the total.

Step 4: Adding and Removing Food Items

Give the user the option to add more food items to their meal plan from the food database, or remove existing items. When the user chooses to add an item, redirect them to the food database search screen, and after they've selected a food item, add it to the appropriate meal. When the user chooses to remove an item, simply remove it from the meal plan object.

Step 5: Saving the Meal Plan

Finally, consider how you want to handle data persistence. When the user closes and reopens the app, their meal plan should be saved.

Grading grid​

Here is the grading grid for this project. Note that bonus points can be awarded for outstanding work or additional features (using an external library, outstanding styling, adding an icon or a splashcreen...). Please be creative :)

CriteriaUnsatisfactorySatisfactoryGoodExcellentOutstanding
Project Setup & Code Organization (2 points)Project setup is incorrect and/or code is disorganized or unreadable.Project setup is mostly correct and code is somewhat organized and readable.Project setup is correct, code is organized, and most naming conventions are followed.Project setup is correct and efficient, code is well-organized, and naming conventions are followed.Project setup is correct and efficient, code is extremely well-organized, with clear, thoughtful naming conventions.
Implementation of Health Goals (5 points)The health goals functionality is missing or implemented incorrectly.The health goals functionality is partially implemented, with some minor errors.The health goals functionality is mostly implemented correctly and works as expected.The health goals functionality is fully implemented, works as expected, and includes robust error checking.The health goals functionality is fully implemented, works as expected, includes robust error checking, and demonstrates a deep understanding of the underlying concepts.
Implementation of Food Database (5 points)The food database functionality is missing or implemented incorrectly.The food database functionality is partially implemented, with some minor errors.The food database functionality is mostly implemented correctly and works as expected.The food database functionality is fully implemented, works as expected, and includes robust error checking.The food database functionality is fully implemented, works as expected, includes robust error checking, and demonstrates a deep understanding of the underlying concepts.
Implementation of Meal Planning (5 points)The meal planning functionality is missing or implemented incorrectly.The meal planning functionality is partially implemented, with some minor errors.The meal planning functionality is mostly implemented correctly and works as expected.The meal planning functionality is fully implemented, works as expected, and includes robust error checking.The meal planning functionality is fully implemented, works as expected, includes robust error checking, and demonstrates a deep understanding of the underlying concepts.
UI Design & Styling (3 points)The application's UI is poorly designed and/or styled.The application's UI is somewhat well-designed and styled, with some minor issues.The application's UI is well-designed and styled, and is mostly consistent across the application.The application's UI is very well-designed and styled, and is consistent across the application.The application's UI is exceptionally well-designed and styled, demonstrating a high level of creativity and attention to detail, and is consistent across the application.
Overall FunctionalityThe application has many bugs or is non-functional.The application has some minor bugs, but is mostly functional.The application is functional and behaves mostly as expected.The application is fully functional, behaves as expected, and includes robust error checking.The application is fully functional, behaves as expected, includes robust error checking, and demonstrates a deep understanding of the underlying concepts.

Deliverables​

  • Project Setup and Code Repository: Students should deliver a properly setup project with a GitHub repository. The repository should contain clear, well-organized code and a README file describing your team, the project, how to set it up, and how to use it. Important: I need to see the two teammates git users committing to the project, otherwise you'll face a penalty of 5 points
  • Documentation: Objective, application's architecture, succeded features, unsucceded features, roadmap and screenshots, and the difficulties you faced while developing it.
  • Demo: Students should prepare a video presentation showcasing their application and all the requested features. You face a penalty of 5 points if the demo is not included.

Please put the documentation (as a PDF) and the demo (as a MP4 video) in the repo.

Remember, these deliverables are not just about completing the project but also about demonstrating a clear understanding of the underlying concepts and skills. It's important to take the time to understand each step, ask questions when necessary, and strive for continuous learning and improvement.

Deadline​

The final project, including all deliverables, must be submitted no later than 23:59 on June 21, 2023. Please note that late submissions may not be accepted, so plan your work accordingly to meet this deadline.

· 12 min read
Youcef

Exercise 1: Adding Navigation to an Expo App.​

// App.js

import React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import HomeScreen from './screens/HomeScreen';
import DetailsScreen from './screens/DetailsScreen';

const Stack = createStackNavigator();

function App() {
return (
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen name="Home" component={HomeScreen} />
<Stack.Screen name="Details" component={DetailsScreen} />
</Stack.Navigator>
</NavigationContainer>
);
}

export default App;
// HomeScreen.js

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

function HomeScreen({ navigation }) {
return (
<View>
<Button
title="Go to Details"
onPress={() => navigation.navigate('Details')}
/>
</View>
);
}

export default HomeScreen;
// DetailsScreen.js

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

function DetailsScreen() {
return (
<View>
<Text>Details Screen</Text>
</View>
);
}

export default DetailsScreen;

Explanation:

  1. In App.js, we import the necessary components from React Navigation and the screen components (HomeScreen and DetailsScreen).
  2. We create a Stack navigator using createStackNavigator and wrap it inside the NavigationContainer.
  3. Inside the Stack.Navigator, we define two screens: Home and Details. We associate each screen with its corresponding component.
  4. In HomeScreen.js, we render a simple View component with a Button. The onPress event of the button uses the navigation.navigate function to navigate to the Details screen.
  5. In DetailsScreen.js, we render a simple View component with a Text component to display the details screen.

To run the app, make sure you have the required dependencies installed. You can do this by running npm install or yarn in the project directory. Then, run expo start to start the Expo development server. You can choose to run the app on an emulator/simulator or scan the QR code using the Expo Go app on your mobile device.

When you open the app, you will see the Home screen with a button. Pressing the button will navigate you to the Details screen, which will display the text "Details Screen".

Exercise 2: Creating Screens and Navigating Between Them.​

// App.js

import React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import HomeScreen from './screens/HomeScreen';
import DetailsScreen from './screens/DetailsScreen';
import ProfileScreen from './screens/ProfileScreen';
import SettingsScreen from './screens/SettingsScreen';

const Tab = createBottomTabNavigator();

function App() {
return (
<NavigationContainer>
<Tab.Navigator>
<Tab.Screen name="Home" component={HomeScreen} />
<Tab.Screen name="Details" component={DetailsScreen} />
<Tab.Screen name="Profile" component={ProfileScreen} />
<Tab.Screen name="Settings" component={SettingsScreen} />
</Tab.Navigator>
</NavigationContainer>
);
}

export default App;
// HomeScreen.js, DetailsScreen.js, ProfileScreen.js, SettingsScreen.js

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

function HomeScreen() {
return (
<View>
<Text>Home Screen</Text>
</View>
);
}

function DetailsScreen() {
return (
<View>
<Text>Details Screen</Text>
</View>
);
}

function ProfileScreen() {
return (
<View>
<Text>Profile Screen</Text>
</View>
);
}

function SettingsScreen() {
return (
<View>
<Text>Settings Screen</Text>
</View>
);
}

export { HomeScreen, DetailsScreen, ProfileScreen, SettingsScreen };

Explanation:

  1. In App.js, we import the necessary components from React Navigation and the screen components (HomeScreen, DetailsScreen, ProfileScreen, and SettingsScreen).
  2. We create a Tab navigator using createBottomTabNavigator and wrap it inside the NavigationContainer.
  3. Inside the Tab.Navigator, we define four screens: Home, Details, Profile, and Settings. We associate each screen with its corresponding component.
  4. Each screen component (HomeScreen, DetailsScreen, ProfileScreen, and SettingsScreen) renders a simple View component with a Text component to display the screen's name.

To run the app, make sure you have the required dependencies installed. You can do this by running npm install or yarn in the project directory. Then, run expo start to start the Expo development server. You can choose to run the app on an emulator/simulator or scan the QR code using the Expo Go app on your mobile device.

When you open the app, you will see a bottom tab bar with four tabs: Home, Details, Profile, and Settings. Each tab will display its respective screen with the corresponding text.

Exercise 3: Passing Parameters to Routes and Configuring Header Bar.​

// App.js

import React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import HomeScreen from './screens/HomeScreen';
import DetailsScreen from './screens/DetailsScreen';

const Stack = createStackNavigator();

function App() {
return (
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen name="Home" component={HomeScreen} />
<Stack.Screen name="Details" component={DetailsScreen} />
</Stack.Navigator>
</NavigationContainer>
);
}

export default App;
// HomeScreen.js

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

function HomeScreen({ navigation }) {
const goToDetails = () => {
navigation.navigate('Details', { itemName: 'React Native Book' });
};

return (
<View>
<Button title="Go to Details" onPress={goToDetails} />
</View>
);
}

export default HomeScreen;
// DetailsScreen.js

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

function DetailsScreen({ route }) {
const { itemName } = route.params;

return (
<View>
<Text>{itemName}</Text>
</View>
);
}

export default DetailsScreen;

Explanation:

  1. In App.js, we import the necessary components from React Navigation and the screen components (HomeScreen and DetailsScreen).
  2. We create a Stack navigator using createStackNavigator and wrap it inside the NavigationContainer.
  3. Inside the Stack.Navigator, we define two screens: Home and Details. We associate each screen with its corresponding component.
  4. In HomeScreen.js, we define a function goToDetails that uses the navigation.navigate function to navigate to the Details screen and pass a parameter itemName with the value "React Native Book".
  5. The HomeScreen component renders a simple View component with a Button component. When the button is pressed, it calls the goToDetails function.
  6. In DetailsScreen.js, we access the passed parameter itemName using route.params and display it in the Text component.

To run the app, make sure you have the required dependencies installed. You can do this by running npm install or yarn in the project directory. Then, run expo start to start the Expo development server. You can choose to run the app on an emulator/simulator or scan the QR code using the Expo Go app on your mobile device.

When you open the app, you will see the Home screen with a button. Pressing the button will navigate you to the Details screen, which will display the text "React Native Book".

Exercise 4: Counter App​

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

const CounterApp = () => {
const [count, setCount] = useState(0);

const incrementCount = () => {
setCount(prev => prev + 1);
};

const decrementCount = () => {
setCount(prev => prev - 1);
};

return (
<View style={styles.container}>
<Text style={styles.counterText}>{count}</Text>
<View style={styles.buttonContainer}>
<Button title="+" onPress={incrementCount} />
<Button title="-" onPress={decrementCount} />
</View>
</View>
);
};

const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
counterText: {
fontSize: 24,
fontWeight: 'bold',
marginBottom: 20,
},
buttonContainer: {
flexDirection: 'row',
},
});

export default CounterApp;

To use this solution, follow these steps:

  1. Initialize a new React Native project using Expo CLI.
  2. Create a new file called CounterApp.js and paste the above code into it.
  3. Save the file and open your main App.js file.
  4. Import the CounterApp component using import CounterApp from './CounterApp'.
  5. Replace the content of the return statement in your main component with <CounterApp />.
  6. Save the changes and run your React Native application using the Expo client or simulator.

This solution creates a counter application where the count is stored in the count state variable. Pressing the "+" button increments the count, and pressing the "-" button decrements it. The current count is displayed using the Text component. Styling is applied using the StyleSheet component.

Feel free to modify the styles and enhance the user interface as per your requirements.

Exercise 5: Toggle Switch​

Certainly! Here's a solution to Exercise 2: Toggle Switch using React Native and the useEffect hook:

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

const ToggleSwitch = () => {
const [isOn, setIsOn] = useState(false);

const toggleSwitch = () => {
setIsOn(!isOn);
};

useEffect(() => {
// Perform any additional logic or actions when the switch state changes
console.log('Switch state changed:', isOn);
}, [isOn]);

return (
<View style={styles.container}>
<TouchableOpacity
style={[styles.switch, isOn ? styles.switchOn : styles.switchOff]}
onPress={toggleSwitch}
>
<Text style={styles.switchText}>{isOn ? 'ON' : 'OFF'}</Text>
</TouchableOpacity>
</View>
);
};

const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
switch: {
paddingVertical: 10,
paddingHorizontal: 20,
borderRadius: 20,
},
switchOn: {
backgroundColor: 'green',
},
switchOff: {
backgroundColor: 'red',
},
switchText: {
fontSize: 18,
color: 'white',
},
});

export default ToggleSwitch;

To use this solution, follow these steps:

  1. Initialize a new React Native project using Expo CLI.
  2. Create a new file called ToggleSwitch.js and paste the above code into it.
  3. Save the file and open your main App.js file.
  4. Import the ToggleSwitch component using import ToggleSwitch from './ToggleSwitch'.
  5. Replace the content of the return statement in your main component with <ToggleSwitch />.
  6. Save the changes and run your React Native application using the Expo client or simulator.

This solution creates a toggle switch component that allows the user to toggle the switch state between "ON" and "OFF". The switch state is stored in the isOn state variable, and it is updated when the user presses the toggle switch using the toggleSwitch function. The useEffect hook is used to perform additional logic or actions whenever the switch state changes. In this example, it simply logs the switch state to the console.

Styling is applied using the StyleSheet component to create a visual representation of the toggle switch. The switch appearance changes based on the isOn state, with different background colors applied for the "ON" and "OFF" states.

Feel free to modify the styles and enhance the user interface as per your requirements.

Exercise 6: Random Quote Generator​

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

const QuoteGenerator = () => {
const [quote, setQuote] = useState('');

useEffect(() => {
fetchQuote();
}, []);

const fetchQuote = async () => {
try {
const response = await fetch('https://type.fit/api/quotes');
const data = await response.json();
const randomIndex = Math.floor(Math.random() * data.length);
const randomQuote = data[randomIndex].text;
setQuote(randomQuote);
} catch (error) {
console.error('Error fetching quote:', error);
}
};

return (
<View style={styles.container}>
<Text style={styles.quoteText}>{quote}</Text>
<Button title="New Quote" onPress={fetchQuote} />
</View>
);
};

const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
quoteText: {
fontSize: 18,
marginHorizontal: 20,
marginBottom: 20,
textAlign: 'center',
},
});

export default QuoteGenerator;

To use this solution, follow these steps:

  1. Initialize a new React Native project using Expo CLI.
  2. Create a new file called QuoteGenerator.js and paste the above code into it.
  3. Save the file and open your main App.js file.
  4. Import the QuoteGenerator component using import QuoteGenerator from './QuoteGenerator'.
  5. Replace the content of the return statement in your main component with <QuoteGenerator />.
  6. Save the changes and run your React Native application using the Expo client or simulator.

This solution creates a quote generator application that fetches a random quote from the "https://type.fit/api/quotes" API using the fetch function inside the fetchQuote function. The fetched quote is stored in the quote state variable and displayed using the Text component. Pressing the "New Quote" button triggers the fetchQuote function again to fetch a new random quote. Styling is applied using the StyleSheet component.

Make sure to handle any errors that may occur during the API call. Feel free to modify the styles and enhance the user interface as per your requirements.

Exercise 7: Real-time Weather Updates​

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

const WeatherApp = () => {
const [weatherData, setWeatherData] = useState(null);

useEffect(() => {
fetchWeatherData();
const interval = setInterval(fetchWeatherData, 10000); // Fetch data every 10 seconds
return () => clearInterval(interval); // Clear interval on component unmount
}, []);

const fetchWeatherData = async () => {
try {
const response = await fetch('https://api.open-meteo.com/v1/forecast?latitude=48.85&longitude=2.35&current_weather=true&&daily=precipitation_probability_mean&timezone=auto');
const data = await response.json();
setWeatherData(data);
} catch (error) {
console.error('Error fetching weather data:', error);
}
};

return (
<View style={styles.container}>
{weatherData ? (
<View>
<Text style={styles.weatherText}>
Temperature: {weatherData.current_weather.temperature}°C
</Text>
<Text style={styles.weatherText}>
Precipitation probability: {weatherData.daily.precipitation_probability_mean[0]}%
</Text>
<Text style={styles.weatherText}>
Wind Speed: {weatherData.current_weather.windspeed} km/h
</Text>
</View>
) : (
<Text>Loading weather data...</Text>
)}
</View>
);
};

const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
weatherText: {
fontSize: 18,
marginBottom: 10,
},
});

export default WeatherApp;

To use this solution, follow these steps:

  1. Initialize a new React Native project using Expo CLI.
  2. Create a new file called WeatherApp.js and paste the above code into it.
  3. Save the file and open your main App.js file.
  4. Import the WeatherApp component using import WeatherApp from './WeatherApp'.
  5. Replace the content of the return statement in your main component with <WeatherApp />.
  6. Save the changes and run your React Native application using the Expo client or simulator.

This solution creates a weather application that fetches weather data from the "https://api.open-meteo.com/weather" API using the fetch function inside the fetchWeatherData function. The fetched data is stored in the weatherData state variable and displayed using the Text component. The weather data includes temperature, humidity, and wind speed. The application fetches data initially when the component mounts and then at regular intervals (every 5 minutes) using the setInterval function.

Make sure to handle any errors that may occur during the API call. Feel free to modify the styles and enhance the user interface as per your requirements.

· 5 min read
Youcef

Setup​

  1. Create a new Expo project
  2. Install eslint and prettier
  3. Run the app on your phone
  4. Try to run your app on a simulator

Exercise 1: Adding Navigation to an Expo App​

Objective: Implement navigation in an Expo app using React Navigation.

Instructions:

  1. Create a new Expo app.
  2. Install React Navigation packages
  3. Create two screens: HomeScreen and DetailsScreen.
  4. Set up a Stack Navigator in your app to navigate between the screens.
  5. Configure the Stack Navigator to show the HomeScreen as the initial route.
  6. Add a button in the HomeScreen that navigates to the DetailsScreen when pressed.

Exercise 2: Creating Screens and Navigating Between Them​

Objective: Create multiple screens and navigate between them using React Navigation.

Instructions:

  1. Add two more screens to your Expo app: ProfileScreen and SettingsScreen.
  2. Create a Bottom Tab Navigator to switch between the screens.
  3. Configure the Tab Navigator to show the HomeScreen as the initial route.
  4. Add buttons or icons to each screen that navigate to the corresponding screen when pressed.

Exercise 3: Passing Parameters to Routes and Configuring Header Bar​

Objective: Pass parameters to routes and configure the header bar in a React Native app.

Instructions:

  1. Modify the DetailsScreen to receive a parameter when navigating to it.
  2. Pass a parameter from the HomeScreen to the DetailsScreen when navigating.
  3. Display the received parameter on the DetailsScreen.
  4. Configure the header bar of the DetailsScreen to display a title based on the received parameter.
  5. Add a header button to the DetailsScreen that performs a specific action when pressed.

Exercise 4: Counter App​

Objective: Create a simple counter application using React Native and the useState hook. The counter should display a number and have two buttons: one for incrementing the count and another for decrementing it.

Instructions:

  1. Create a new Expo app or use the current one.
  2. Create a functional component called CounterApp.
  3. Import the necessary React Native components (Text, View, Button, etc.) from the react-native package.
  4. Inside the CounterApp component, use the useState hook to define a state variable called count and a function called setCount to update it.
  5. Render a View component that contains a Text component displaying the current value of count.
  6. Add two Button components below the Text component: one with the label "+" and another with the label "-".
  7. Attach onPress handlers to each button that call the appropriate function to increment or decrement the count state variable using setCount.
  8. Style the components as desired to improve the user interface.
  9. Test the application in the Expo client or simulator.

Exercise 5: Toggle Switch​

Objective: Create a toggle switch component using React Native and the useState hook. The toggle switch should have an initial state (on/off) and change its state when the user taps on it.

Instructions:

  1. Create a new Expo app or use the current one.
  2. Define a functional component called ToggleSwitch.
  3. Import the necessary React Native components (Text, View, TouchableOpacity, etc.) from the react-native package.
  4. Inside the ToggleSwitch component, use the useState hook to define a state variable called isOn and a function called setIsOn to update it.
  5. Render a View component that represents the toggle switch.
  6. Inside the View component, render a Text component displaying the current state (isOn).
  7. Add a TouchableOpacity component inside the View component that wraps the entire toggle switch.
  8. Attach an onPress handler to the TouchableOpacity component that calls the setIsOn function to toggle the isOn state variable.
  9. Style the components to create a visual representation of the toggle switch, such as using different colors or icons to represent the different states.
  10. Test the toggle switch component in the Expo client or simulator.

Exercise 6: Random Quote Generator​

Objective: Create a simple random quote generator application using React Native and the useEffect hook. The application should fetch a random quote from an API and display it on the screen.

Instructions:

  1. Create a functional component called QuoteGenerator.
  2. Import the necessary React Native components (Text, View, etc.) from the react-native package.
  3. Inside the QuoteGenerator component, use the useState hook to define a state variable called quote and a function called setQuote to update it.
  4. Use the useEffect hook to fetch a random quote from the API https://type.fit/api/quotes when the component mounts. You can use the fetch function or a library like Axios to make the API call.
  5. Update the quote state variable with the fetched quote.
  6. Render a View component that contains a Text component displaying the current value of the quote state variable.
  7. Style the components as desired to improve the user interface.
  8. Test the application in the Expo client or simulator.

Exercise 7: Real-time Weather Updates​

Objective: Create a real-time weather update application using React Native and the useEffect hook. The application should fetch weather data from an API and display it on the screen, updating the data at regular intervals.

Instructions:

  1. Create a new Expo app or use the current one.
  2. Define a functional component called WeatherApp.
  3. Import the necessary React Native components (Text, View, etc.) from the react-native package.
  4. Inside the WeatherApp component, use the useState hook to define a state variable called weatherData and a function called setWeatherData to update it.
  5. Use the useEffect hook to fetch weather data from the API https://open-meteo.com/ when the component mounts and at regular intervals (e.g., every 5 minutes). You can use the fetch function or a library like Axios to make the API call.
  6. Update the weatherData state variable with the fetched weather data.
  7. Render a View component that contains Text components displaying the relevant weather information from the weatherData state variable (e.g., temperature, humidity, etc.).
  8. Style the components as desired to improve the user interface.
  9. Test the application in the Expo client or simulator.

· 5 min read
Youcef

Exercise 1:​

Here's an example of how you can achieve the desired layout using React Native and Expo:

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

const Exercise1 = () => {
return (
<View style={styles.container}>
<Text style={styles.header}>Here are my boxes</Text>
<View style={styles.boxContainer}>
<Rectangle color="#2aa198" name="Cyan: #2aa198" />
<Rectangle color="#268bd2" name="Blue: #268bd2" />
<Rectangle color="#d33682" name="Magenta: #d33682" />
<Rectangle color="#cb4b16" name="Orange: #cb4b16" />
</View>
</View>
);
};

const Rectangle = ({ color, name }) => {
return (
<View style={[styles.rectangle, { backgroundColor: color }]}>
<Text style={styles.rectangleText}>{name}</Text>
</View>
);
};

const styles = StyleSheet.create({
container: {
flex: 1,
padding: 16,
alignItems: 'center',
},
header: {
fontSize: 24,
fontWeight: 'bold',
marginBottom: 16,
},
boxContainer: {
justifyContent: 'center',
},
rectangle: {
width: 200,
height: 50,
marginBottom: 8,
justifyContent: 'center',
alignItems: 'center',
},
rectangleText: {
color: 'white',
fontWeight: 'bold',
},
});

export default Exercise1;

You can use the Exercise1 component in your main app file to display the header and rectangles with their respective colors and names.

Exercise 2:​

Here's an example of how you can create three centered squares with unique background colors using shared styles:

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

const Exercise2 = () => {
return (
<View style={styles.container}>
<View style={[styles.square, styles.square1]} />
<View style={[styles.square, styles.square2]} />
<View style={[styles.square, styles.square3]} />
</View>
);
};

const sharedStyles = StyleSheet.create({
square: {
width: 100,
height: 100,
margin: 8,
},
});

const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
},
square1: {
backgroundColor: 'red',
},
square2: {
backgroundColor: 'green',
},
square3: {
backgroundColor: 'blue',
},
});

export default Exercise2;

You can use the Exercise2 component in your main app file to display the three centered squares with their respective colors.

Exercise 3:​

Here's an example of how you can create a profile screen layout using the flex property:

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

const Exercise3 = () => {
return (
<View style={styles.container}>
<View style={styles.profilePictureContainer}>
<Image
source={require('./profile-picture.jpg')}
style={styles.profilePicture}
/>
</View>
<View style={styles.userInfoContainer}>
<Text style={styles.name}>John Doe</Text>
<Text style={styles.bio}>Software Developer</Text>
</View>
<View style={

styles.postsContainer}>
<Text style={styles.postsTitle}>Posts</Text>
<Text style={styles.post}>Post 1</Text>
<Text style={styles.post}>Post 2</Text>
<Text style={styles.post}>Post 3</Text>
</View>
</View>
);
};

const styles = StyleSheet.create({
container: {
flex: 1,
padding: 16,
},
profilePictureContainer: {
alignItems: 'center',
marginTop: 16,
},
profilePicture: {
width: 150,
height: 150,
borderRadius: 75,
},
userInfoContainer: {
alignItems: 'center',
marginTop: 16,
},
name: {
fontSize: 24,
fontWeight: 'bold',
},
bio: {
fontSize: 16,
marginTop: 8,
},
postsContainer: {
flex: 1,
marginTop: 16,
},
postsTitle: {
fontSize: 20,
fontWeight: 'bold',
marginBottom: 8,
},
post: {
fontSize: 16,
marginBottom: 4,
},
});

export default Exercise3;

You can use the Exercise3 component in your main app file to display the profile screen layout.

Exercise 4:​

Here's an example of how you can create a contact list using the FlatList component:

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

const ContactScreen = () => {
const contacts = [
{ id: '1', name: 'John Doe', phoneNumber: '123-456-7890' },
{ id: '2', name: 'Jane Smith', phoneNumber: '987-654-3210' },
{ id: '3', name: 'Alice Johnson', phoneNumber: '555-123-4567' },
];

const renderContactItem = ({ item }) => (
<View style={styles.item}>
<Text style={styles.name}>{item.name}</Text>
<Text style={styles.phoneNumber}>{item.phoneNumber}</Text>
</View>
);

return (
<View style={styles.container}>
<FlatList
data={contacts}
renderItem={renderContactItem}
keyExtractor={(item) => item.id}
ItemSeparatorComponent={() => <View style={styles.separator} />}
/>
</View>
);
};

const styles = StyleSheet.create({
container: {
flex: 1,
padding: 16,
},
item: {
paddingVertical: 8,
},
name: {
fontSize: 16,
fontWeight: 'bold',
},
phoneNumber: {
fontSize: 14,
color: '#666',
},
separator: {
height: 1,
backgroundColor: '#ccc',
},
});

export default ContactScreen;

You can use the ContactScreen component in your main app file to display the contact list using the FlatList component.

Exercise 5:​

Here's an example of how you can group contacts by the first letter of their names using the SectionList component:

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

const SectionContactScreen = () => {
const contacts = [
{ id: '1', name: 'John Doe', phoneNumber: '123-456-7890' },
{ id: '2', name: 'Jane Smith', phoneNumber: '987-654-3210' },


{ id: '3', name: 'Alice Johnson', phoneNumber: '555-123-4567' },
// ...more contacts
];

const contactsBySection = contacts.reduce((sections, contact) => {
const firstLetter = contact.name.charAt(0).toUpperCase();
if (!sections[firstLetter]) {
sections[firstLetter] = { title: firstLetter, data: [] };
}
sections[firstLetter].data.push(contact);
return sections;
}, {});

const sections = Object.values(contactsBySection);

const renderContactItem = ({ item }) => (
<View style={styles.item}>
<Text style={styles.name}>{item.name}</Text>
<Text style={styles.phoneNumber}>{item.phoneNumber}</Text>
</View>
);

const renderSectionHeader = ({ section }) => (
<Text style={styles.sectionHeader}>{section.title}</Text>
);

return (
<View style={styles.container}>
<SectionList
sections={sections}
renderItem={renderContactItem}
renderSectionHeader={renderSectionHeader}
keyExtractor={(item) => item.id}
ItemSeparatorComponent={() => <View style={styles.separator} />}
/>
</View>
);
};

const styles = StyleSheet.create({
container: {
flex: 1,
padding: 16,
},
item: {
paddingVertical: 8,
},
name: {
fontSize: 16,
fontWeight: 'bold',
},
phoneNumber: {
fontSize: 14,
color: '#666',
},
sectionHeader: {
fontSize: 18,
fontWeight: 'bold',
backgroundColor: '#f5f5f5',
paddingVertical: 8,
paddingHorizontal: 16,
},
separator: {
height: 1,
backgroundColor: '#ccc',
},
});

export default SectionContactScreen;

You can use the SectionContactScreen component in your main app file to display the contact list grouped by the first letter of their names using the SectionList component.

· 3 min read
Youcef

Setup

  1. Create a new Expo project
  2. Install eslint and prettier
  3. Run the app on your phone
  4. Try to run your app on a simulator

Exercise 1

Create a header with a text saying "Here are my boxes". The font size should be 24 and the font weight should be bold. Below that, create a column of 4 rectangles vertically centered. Each rectangle should have a different color. Inside the rectangle, please write the name of the color.

For example:

Cyan: #2aa198
Blue: #268bd2
Magenta: #d33682
Orange: #cb4b16

Exercise 2

Create 3 squares that are vertically and horizontally centered. Each square should have a unique background color but all shared styles should only be defined once.

Exercise 3

In this exercise, you'll be using the flex property to create a layout for a profile screen. The screen will have a profile picture at the top, followed by the user's name and a short bio, and then a section for their posts. Use the Image component for the profile picture, and Text components for the user's name, bio, and posts. Create a new style using StyleSheet and apply it to your components. Use the flex property to make sure that the posts section takes up the majority of the screen, while the profile picture, name, and bio take up less space.

Exercise 4

In this exercise, you will create a contact list using the FlatList component.

Create a new screen in your Expo project, let's call it ContactScreen. Define an array of contact objects, each with a photo, a name and phoneNumber property. Render a FlatList that maps each of these contacts into a Text component displaying the contact's name and phone number. Add the keyExtractor prop to the FlatList that returns a unique key string for each item. Use the ItemSeparatorComponent prop to render a separator between each item in the list.

Exercise 5

For this exercise, you'll modify the contact list from Exercise 1 to group the contacts by the first letter of their names using the SectionList component.

Create a new screen in your Expo project, let's call it SectionContactScreen. Convert your contacts array into a sectioned format that SectionList requires. It should be an array of objects, each with a title property (the first letter of the names) and a data property (an array of contacts with that initial). Render a SectionList. The renderItem prop should be a function that renders a Text component for each contact, and the renderSectionHeader prop should be a function that renders a Text component for each section title. As in Exercise 1, include a keyExtractor prop and an ItemSeparatorComponent prop.

· One min read
Youcef
JavaScript

FreeCodeCamp​

Rendez-vous sur FreeCodeCamp et créez votre compte.

Tutoriel JavaScript​

L'objectif est de maîtriser :

Quiz​

Lors du prochain cours, le 10/05/2023, vous aurez un quiz de 20 minutes sur JavaScript afin de valider vos connaissances.