Open In App

Create Jokes Generator App using React-Native

Last Updated : 25 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we are going to build a joke generator app using react native. React Native enables you to master the­ designing an elegant and dynamic use­r interface while e­ffortlessly retrieving joke­s from external APIs.

Playground

Note: This Section is to interact with the app which you are going to build.


Prerequisites / Technologies Used

Step-by-Step Implementation

Step 1: Create a React Native Project

Now, create a project with the following command.

npx create-expo-app app-name --template

Note: Replace the app-name with your app name for example : react-native-demo-app

Next, you might be asked to choose a template. Select one based on your preference as shown in the image below. I am selecting the blank template because it will generate a minimal app that is as clean as an empty canvas in JavaScript.

It completes the project creation and displays a message: "Your Project is ready!" as shown in the image below.

Now go into your project folder, i.e., react-native-demo

cd app-name

Project Structure:

Step 2: Run  Application

Start the server by using the following command.

npx expo start

Then, the application will display a QR code.

  • For the Android users,
    • For the Android Emulator, press " a" as mentioned in the image below.
    • For the Physical Device, download the " Expo Go " app from the Play Store. Open the app, and you will see a button labeled " Scan QR Code. " Click that button and scan the QR code; it will automatically build the Android app on your device.
  • For iOS users, simply scan the QR code using the Camera app.
  • If you're using a web browser, it will provide a local host link that you can use as mentioned in the image below.

Step 3: Add dependencies

Add the below dependencies in package.json.

package.json:

{
"dependencies": {
"react-native-paper": "^5.14.0",
}
}

Now, run the following command in the terminal to install the above dependencies.

npm install

Step 4: Start Coding

- Approach:

The "Random Joke­s Generator" app seamlessly retrieves joke­s from an external API (https://icanhazdadjoke.com/), continuous supply of humor. Its user-friendly inte­rface boasts a well-structured layout that consists of a title­, a joke container, and an easily acce­ssible "Get a Joke" button, e­nabling smooth interaction. The app enhance­s the visual experie­nce by presenting joke­s in an elegant white containe­r with rounde­d corners and shadows. With just a simple click on the­ button, users can enjoy fresh joke­s and stay engaged.

Let's dive into the code in detail.

Import libraries:

Import required libraries at the top of the file.

JavaScript
// Import useState hook from React for state management
import { useState } from "react";
// Import necessary components from react-native
import {
	View,              // Container component for layout
	Text,              // Component for displaying text
	StyleSheet,        // Utility for creating styles
	TouchableOpacity,  // Button-like component for touch handling
} from "react-native";

StyleSheet:

Create a StyleSheet to style components like container, title, jokeContainer, etc.

JavaScript
// Styles for the components
const styles = StyleSheet.create({
	container: {
		flex: 1,                         // Take up the full screen
		backgroundColor: "#eee",         // Light gray background
		alignItems: "center",            // Center items horizontally
		justifyContent: "center",        // Center items vertically
		padding: 16,                     // Padding around the container
	},
	title: {
		fontSize: 28,                    // Large font size
		fontWeight: "bold",              // Bold text
		color: "#333739",                // Dark text color
		marginBottom: 24,                // Space below the title
		textAlign: "center",             // Center the text
	},
	jokeContainer: {
		backgroundColor: "white",        // White background for the joke
		borderRadius: 15,                // Rounded corners
		padding: 20,                     // Padding inside the container
		marginBottom: 24,                // Space below the joke
		width: "100%",                   // Full width
		alignItems: "center",            // Center content horizontally
		shadowColor: "black",            // Shadow color
		shadowOffset: { width: 1, height: 2 }, // Shadow offset
		shadowRadius: 15,                // Shadow blur radius
		shadowOpacity: 1,                // Shadow opacity
		elevation: 4,                    // Android shadow
	},
	jokeText: {
		fontSize: 22,                    // Font size for the joke
		fontWeight: "300",               // Light font weight
		lineHeight: 30,                  // Line height for readability
		color: "#333739",                // Text color
		textAlign: "center",             // Center the text
	},
	button: {
		padding: 16,                     // Padding inside the button
		backgroundColor: "green",        // Green background
		borderRadius: 10,                // Rounded corners
		shadowColor: "black",            // Shadow color
		shadowOffset: { width: 1, height: 2 }, // Shadow offset
		shadowRadius: 15,                // Shadow blur radius
		shadowOpacity: 1,                // Shadow opacity
		elevation: 4,                    // Android shadow
	},
	buttonText: {
		fontSize: 20,                    // Font size for button text
		color: "white",                  // White text color
		fontWeight: "bold",              // Bold text
	},
});

Title Text:

This title explains what the app does. We use the text "Random Jokes Generator" to show that the app is to generate a random joke.

JavaScript
{/* Title text */}
<Text style={styles.title}>
	Random Jokes Generator
</Text>

- Jokes Container:

This joke container is made using a Text component inside a View component, with some styling. It shows the joke each time the "joke" state variable changes.

JavaScript
// State variable to hold the current joke
const [joke, setJoke] = useState("");

{/* Container for the joke text */}
<View style={styles.jokeContainer}>
	<Text style={styles.jokeText}>{joke}</Text>
</View>

- Get a Joke button:

This button is used to call the getJoke function, which generates a random joke. It is made using a Text component that shows the words "Get a Joke" inside a TouchableOpacity component.

JavaScript
{/* Button to fetch a new joke */}
<TouchableOpacity
	style={styles.button}
	onPress={getJoke}
>
	<Text style={styles.buttonText}>
		Get a Joke
	</Text>
</TouchableOpacity>


- getJoke function:

This is used to make a get request from provided URL inside the code and set the joke to joke state variable by calling setJoke useState function.

JavaScript
// State variable to hold the current joke
const [joke, setJoke] = useState("");

// Function to fetch a random joke from the API
const getJoke = async () => {
    try {
        // Make a GET request to the joke API with JSON
        // response
        const response = await fetch(
            "https://icanhazdadjoke.com/",
            {
                headers : {
                    Accept :
                        "application/json", // Request JSON
                                            // format
                },
            });
        // Parse the JSON response
        const data = await response.json();
        // Update the joke state with the fetched joke
        setJoke(data.joke);
    }
    catch (error) {
        // Log any errors to the console
        console.error(error);
    }
};

Now, wrap all design code with a View component, return it from the App component, and place all methods and useStates within the App component. Ensure to export the App.

Complete Source Code

App.js:

App.js
// Import useState hook from React for state management
import { useState } from "react";
// Import necessary components from react-native
import {
	View,              // Container component for layout
	Text,              // Component for displaying text
	StyleSheet,        // Utility for creating styles
	TouchableOpacity,  // Button-like component for touch handling
} from "react-native";

// Main App component
const App = () => {
	// State variable to hold the current joke
	const [joke, setJoke] = useState("");

	// Function to fetch a random joke from the API
	const getJoke = async () => {
		try {
			// Make a GET request to the joke API with JSON response
			const response = await fetch(
				"https://icanhazdadjoke.com/",
				{
					headers: {
						Accept: "application/json", // Request JSON format
					},
				}
			);
			// Parse the JSON response
			const data = await response.json();
			// Update the joke state with the fetched joke
			setJoke(data.joke);
		} catch (error) {
			// Log any errors to the console
			console.error(error);
		}
	};

	// Render the UI
	return (
		<View style={styles.container}>
			{/* Title text */}
			<Text style={styles.title}>
				Random Jokes Generator
			</Text>
			{/* Container for the joke text */}
			<View style={styles.jokeContainer}>
				<Text style={styles.jokeText}>{joke}</Text>
			</View>
			{/* Button to fetch a new joke */}
			<TouchableOpacity
				style={styles.button}
				onPress={getJoke}
			>
				<Text style={styles.buttonText}>
					Get a Joke
				</Text>
			</TouchableOpacity>
		</View>
	);
};

// Styles for the components
const styles = StyleSheet.create({
	container: {
		flex: 1,                         // Take up the full screen
		backgroundColor: "#eee",         // Light gray background
		alignItems: "center",            // Center items horizontally
		justifyContent: "center",        // Center items vertically
		padding: 16,                     // Padding around the container
	},
	title: {
		fontSize: 28,                    // Large font size
		fontWeight: "bold",              // Bold text
		color: "#333739",                // Dark text color
		marginBottom: 24,                // Space below the title
		textAlign: "center",             // Center the text
	},
	jokeContainer: {
		backgroundColor: "white",        // White background for the joke
		borderRadius: 15,                // Rounded corners
		padding: 20,                     // Padding inside the container
		marginBottom: 24,                // Space below the joke
		width: "100%",                   // Full width
		alignItems: "center",            // Center content horizontally
		shadowColor: "black",            // Shadow color
		shadowOffset: { width: 1, height: 2 }, // Shadow offset
		shadowRadius: 15,                // Shadow blur radius
		shadowOpacity: 1,                // Shadow opacity
		elevation: 4,                    // Android shadow
	},
	jokeText: {
		fontSize: 22,                    // Font size for the joke
		fontWeight: "300",               // Light font weight
		lineHeight: 30,                  // Line height for readability
		color: "#333739",                // Text color
		textAlign: "center",             // Center the text
	},
	button: {
		padding: 16,                     // Padding inside the button
		backgroundColor: "green",        // Green background
		borderRadius: 10,                // Rounded corners
		shadowColor: "black",            // Shadow color
		shadowOffset: { width: 1, height: 2 }, // Shadow offset
		shadowRadius: 15,                // Shadow blur radius
		shadowOpacity: 1,                // Shadow opacity
		elevation: 4,                    // Android shadow
	},
	buttonText: {
		fontSize: 20,                    // Font size for button text
		color: "white",                  // White text color
		fontWeight: "bold",              // Bold text
	},
});

// Export the App component as the default export
export default App;

Output:


Next Article

Similar Reads