Skip to main content

TD n°3 - Navigation & Hooks - Solutions

· 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.