Friday, November 22, 2024
Google search engine
HomeLanguagesCreate Memes Generator App using React-Native

Create Memes Generator App using React-Native

The Me­me Generator App is a mobile­ application that allows users to effortlessly create memes. With its use­r-friendly interface, use­rs can choose from a wide collection of popular me­me templates and add their own customized text to the top and bottom. In this article, we will see how we can build a memes generator application using react native with the help of API.

Preview:

Prerequisites

  • Introduction to React Native
  • React Native Components
  • Expo CLI
  • Node.js and npm (Node Package Manager)

Steps to Create React Native Application

Step 1: Create a react native application by using this command

npx create-expo-app memesGeneratorApp

Step 2: After creating your project folder, i.e. memesGeneratorApp, use the following command to navigate to it:

cd memesGeneratorApp

Project Structure

package.json:

{
  "dependencies": {
    "react-native-paper": "4.9.2",
    "@expo/vector-icons": "^13.0.0"
  }
}

Approach:

The Me­me Generator App utilize­s a straightforward approach to allow users to effortlessly cre­ate a meme. It commences by retrie­ving a diverse compilation of meme­ templates from an exte­rnal API. Users can then choose a template and add their custom text to the top and bottom sections. By simply clicking the “Generate­ Meme” button, the app cle­verly merges the­ chosen template with the­ added text, promptly gene­rating a brand new meme.

Example: In this example,

  • State Management: The component manages state using the useState hook for meme-related data and API response.
  • API Call: It fetches meme data from an API using the fetch function and updates the state with the fetched data.
  • User Interaction: Users can enter top and bottom text, click a button to fetch a random meme, and see it displayed with the entered text.
  • Styling: The component uses inline and StyleSheet styling for layout, buttons, and text, including shadows and borders for aesthetics.
  • Conditional Rendering: It conditionally renders the meme image and text only when imgState is true, controlling the display of the generated meme.

Javascript




//App.js
  
import React, { useState, useEffect } from "react";
import {
    View,
    Text,
    TextInput,
    Button,
    Image,
    StyleSheet,
    TouchableOpacity,
    SafeAreaView,
} from "react-native";
  
export default function Form() {
    const [allMemeData, setMemeAllImages] = useState({});
    const [imgState, setImageState] = useState(false);
    const [meme, setMeme] = useState({
        topText: "",
        bottomText: "",
        randomImage: "",
    });
  
    useEffect(() => {
        async function getMemesApi() {
            try {
                const response = await fetch(
                    "https://api.imgflip.com/get_memes");
                const data = await response.json();
                setMemeAllImages(data);
            } catch (error) {
                console.error("Error fetching memes:", error);
            }
        }
        getMemesApi();
    }, []);
  
    const handleClick = () => {
        const memesArray = allMemeData.data.memes;
        const randomIndex = Math.floor(Math.random() * memesArray.length);
        const imgUrl = memesArray[randomIndex].url;
        setImageState(true);
        setMeme({
            ...meme,
            randomImage: imgUrl,
        });
    };
  
    const handleChange = (name, value) => {
        setMeme({
            ...meme,
            [name]: value,
        });
    };
  
    return (
        <SafeAreaView style={styles.container}>
            <View style={styles.navbar}>
                <Text style={styles.navbarText}>
                    Meme Generator
                </Text>
            </View>
            <View style={styles.formContainer}>
                <View style={styles.inputContainer}>
                    <TextInput
                        style={styles.inputText}
                        onChangeText={(value) =>
                            handleChange("topText", value)}
                        value={meme.topText}
                        placeholder="Enter top text"
                    />
                    <TextInput
                        style={styles.inputText}
                        onChangeText={(value) =>
                            handleChange("bottomText", value)}
                        value={meme.bottomText}
                        placeholder="Enter bottom text"
                    />
                </View>
                <TouchableOpacity style={styles.button}
                    onPress={handleClick}>
                    <Text style={styles.buttonText}>
                        Get a new random meme
                    </Text>
                </TouchableOpacity>
            </View>
            {imgState && (
                <View style={styles.imageContainer}>
                    <Image source={
                        { uri: meme.randomImage }}
                        style={styles.memeImage} />
                    <Text style={styles.memeTextTop}>
                        {meme.topText}</Text>
                    <Text style={styles.memeText}>
                        {meme.bottomText}</Text>
                </View>
            )}
        </SafeAreaView>
    );
}
  
const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: "#f0f0f0",
    },
    navbar: {
        backgroundColor: "green",
        padding: 20,
        alignItems: "center",
    },
    navbarText: {
        color: "white",
        fontSize: 24,
        fontWeight: "bold",
    },
    formContainer: {
        flex: 1,
        justifyContent: "center",
        alignItems: "center",
        backgroundColor: "white",
        margin: 20,
        padding: 20,
        borderRadius: 15,
        elevation: 5,
        shadowColor: "#000",
        shadowOpacity: 1,
        shadowOffset: { width: 3, height: 3 },
    },
    inputContainer: {
        marginBottom: 20,
    },
    inputText: {
        borderBottomWidth: 1,
        borderBottomColor: "#333",
        fontSize: 16,
        paddingVertical: 10,
    },
    button: {
        backgroundColor: "green",
        padding: 12,
        borderRadius: 10,
        width: "100%",
        alignItems: "center",
    },
    buttonText: {
        color: "white",
        fontSize: 18,
        fontWeight: "bold",
    },
    imageContainer: {
        flex: 1,
        justifyContent: "center",
        alignItems: "center",
        marginTop: 20,
    },
    memeImage: {
        width: 300,
        height: 300,
        resizeMode: "contain",
        borderRadius: 10,
        borderWidth: 3,
        borderColor: "#333",
        shadowColor: "#000",
        shadowOpacity: 0.4,
        shadowOffset: { width: 0, height: 4 },
        marginBottom: 20,
    },
    memeTextTop: {
        fontSize: 20,
        fontWeight: "bold",
        position: "absolute",
        top: 30,
        left: 50,
        zIndex: 3,
        color: "crimson",
        textShadowColor: "rgba(0, 0, 0, 0.75)",
        textShadowOffset: { width: -1, height: 1 },
        textShadowRadius: 10,
    },
    memeText: {
        fontSize: 20,
        fontWeight: "bold",
        position: "absolute",
        bottom: 40,
        left: 50,
        zIndex: 3,
        color: "crimson",
        textAlign: "center",
        textShadowColor: "rgba(0, 0, 0, 0.75)",
        textShadowOffset: { width: -1, height: 1 },
        textShadowRadius: 10,
    },
});


Steps to Run: To run react native application use the following command:

npx expo start

To run on Android:

npx react-native run-android

To run on iOS:

npx react-native run-ios

Output:

Create-Memes-Generator-App-using-React-Native

Create Memes Generator App using React-Native

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments