


Building an Interactive Kids Story Generator with React Native and Hugging Face API
In this post, we’ll walk through building a React Native app that generates children’s stories based on prompts and age ranges, using Hugging Face's powerful AI models. The app allows users to enter a prompt, select an age range, and then see a custom story along with a cartoonish image summarizing the story.
Features
- Interactive Story Generation: User input guides the AI to create engaging children’s stories.
- Summarization and Visualization: The story is summarized and displayed alongside an AI-generated image.
- Smooth UI Animation: Animations adapt the UI for keyboard input.
- Navigation and Styling: Using Expo Router for easy navigation and custom styles for an attractive UI.
Let’s break down each part!
Step 1: Setting Up React Native and Hugging Face API
Start by creating a new React Native project with Expo:
npx create-expo-app@latest KidsStoryApp cd KidsStoryApp
Set up Expo Router in your app for easy navigation, and install any additional dependencies you may need, like icons or animations.
Step 2: Creating the Story Generator Home Screen
In the Home.js file, we set up a screen where users can select an age range, enter a story prompt, and press a button to generate a story.
Home.js Code
import React, { useEffect, useRef, useState } from "react"; import { View, Text, TouchableOpacity, StyleSheet, TextInput, Animated, ActivityIndicator, } from "react-native"; import useKeyboardOffsetHeight from "../hooks/useKeyboardOffsetHeight"; import { HUGGING_FACE_KEY } from "../env"; import { useRouter } from "expo-router"; const Home = () => { const ageRanges = ["0-3", "4-6", "7-9"]; const [selectedAgeRange, setSelectedAgeRange] = useState("0-3"); const [textInput, setTextInput] = useState(""); const [isLoading, setIsLoading] = useState(false); const keyboardOffsetHeight = useKeyboardOffsetHeight(); const animatedValue = useRef(new Animated.Value(0)).current; const router = useRouter(); useEffect(() => { Animated.timing(animatedValue, { toValue: keyboardOffsetHeight ? -keyboardOffsetHeight * 0.5 : 0, duration: 500, useNativeDriver: true, }).start(); }, [keyboardOffsetHeight]); const handleAgeRangeSelect = (range) => setSelectedAgeRange(range); const handleShowResult = () => { if (textInput.length > 5) { fetchStory(); } else { alert("Please enter a bit more detail."); } }; async function fetchStory() { setIsLoading(true); try { let message = `Write a simple story for kids about ${textInput} ${ selectedAgeRange ? "for age group " selectedAgeRange : "" }, in plain words. Only provide the story content without any headings, titles, or extra information.`; const response = await fetch( "https://api-inference.huggingface.co/models/meta-llama/Llama-3.2-3B-Instruct/v1/chat/completions", { method: "POST", headers: { Authorization: `Bearer ${HUGGING_FACE_KEY}`, "Content-Type": "application/json", }, body: JSON.stringify({ model: "meta-llama/Llama-3.2-3B-Instruct", messages: [{ role: "user", content: message }], max_tokens: 500, }), } ); if (!response.ok) throw new Error("Failed to fetch story"); const data = await response.json(); const storyContent = data.choices[0].message.content; // Summarize the story const summaryResponse = await fetch( "https://api-inference.huggingface.co/models/meta-llama/Llama-3.2-3B-Instruct/v1/chat/completions", { method: "POST", headers: { Authorization: `Bearer ${HUGGING_FACE_KEY}`, "Content-Type": "application/json", }, body: JSON.stringify({ model: "meta-llama/Llama-3.2-3B-Instruct", messages: [ { role: "user", content: `Summarize this story in a line: "${storyContent}"` }, ], max_tokens: 30, }), }); if (!summaryResponse.ok) throw new Error("Failed to fetch summary"); const summaryData = await summaryResponse.json(); const summaryContent = summaryData.choices[0].message.content; router.push({ pathname: "/detail", params: { story: storyContent, summary: summaryContent }, }); } catch (error) { console.error("Error fetching story or summary:", error); alert("Error fetching story. Please try again."); } finally { setIsLoading(false); } } return ( <Animated.ScrollView bounces={false} keyboardShouldPersistTaps="handled" keyboardDismissMode="on-drag" > <h3> Key Components of Home.js </h3> <ul> <li> <strong>Text Input and Age Selector</strong>: Allows the user to select an age range and enter a story prompt.</li> <li> <strong>Fetch Story</strong>: fetchStory interacts with the Hugging Face API to generate and summarize a story based on the input.</li> <li> <strong>Navigation</strong>: If a story and summary are successfully fetched, the app navigates to the Detail screen to display the results.</li> </ul> <hr> <h3> Step 3: Displaying Story and Image on the Detail Screen </h3> <p><img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/173252011696327.jpg" class="lazy" alt="Building an Interactive Kids Story Generator with React Native and Hugging Face API" /></p> <p>The Detail screen retrieves the generated story, summarizes it, and displays an AI-generated cartoon image related to the story.</p><h4> Detail.js Code </h4> <pre class="brush:php;toolbar:false">import React, { useEffect, useState } from "react"; import { StyleSheet, View, Text, TouchableOpacity, ActivityIndicator, Image, ScrollView } from "react-native"; import { useLocalSearchParams, useRouter } from "expo-router"; import { HUGGING_FACE_KEY } from "../env"; import Ionicons from "@expo/vector-icons/Ionicons"; const Detail = () => { const params = useLocalSearchParams(); const { story, summary } = params; const [imageUri, setImageUri] = useState(null); const [loading, setLoading] = useState(false); const router = useRouter(); useEffect(() => { const fetchImage = async () => { setLoading(true); try { const response = await fetch("https://api-inference.huggingface.co/models/stabilityai/stable-diffusion-xl-base-1.0", { method: "POST", headers: { Authorization: `Bearer ${HUGGING_FACE_KEY}`, "Content-Type": "application/json" }, body: JSON.stringify ({ inputs: `Cartoonish ${summary}`, target_size: { width: 300, height: 300 } }), }); if (!response.ok) throw new Error(`Request failed: ${response.status}`); const blob = await response.blob(); const base64Data = await blobToBase64(blob); setImageUri(`data:image/jpeg;base64,${base64Data}`); } catch (error) { console.error("Error fetching image:", error); } finally { setLoading(false); } }; fetchImage(); }, []); const blobToBase64 = (blob) => { return new Promise((resolve, reject) => { const reader = new FileReader(); reader.onloadend = () => resolve(reader.result.split(",")[1]); reader.onerror = reject; reader.readAsDataURL(blob); }); }; return ( <ScrollView> <h3> Wrapping Up </h3> <p>This app is a great way to combine user input with AI models to create a dynamic storytelling experience. By using React Native, Hugging Face API, and Expo Router, we’ve created a simple yet powerful storytelling app that can entertain kids with custom-made stories and illustrations.</p>
The above is the detailed content of Building an Interactive Kids Story Generator with React Native and Hugging Face API. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.
