Implementing JSON Data & TypeScript Best Practices

0
57

๐Ÿ“Œ SEO Optimization

SEO Title:

โ€œReact Native Word Search: Building a Game with JSON & TypeScriptโ€

Short Meta Description (Max 60 characters):

โ€œCreate a Word Search game in React Native with TypeScript.โ€

Full Meta Description:

โ€œLearn how to build a Word Search game in React Native using Expo Router, Firebase-like JSON data, and TypeScript for structured game logic. Improve UI with ListView and dynamic grid placement.โ€

Keywords:

React Native Word Search, TypeScript in React Native, JSON data in React Native, Expo Router navigation, Firebase JSON game, React Native word grid, React Native puzzle game


๐Ÿ“Œ Introduction

In this tutorial, we will: โœ… Create the โ€œStart Gameโ€ screen with a ListView to select a language.
โœ… Fetch data from a JSON file (similar to Firebase Realtime Database).
โœ… Implement TypeScript best practices for handling structured JSON data.
โœ… Generate a 12ร—12 word search grid using definitions as hidden words.
โœ… Ensure smooth navigation between screens using Expo Router.
โœ… Explain TypeScript features like type definitions and keyof typeof.

By the end of this tutorial, you will:

  • Understand how to properly use TypeScript with JSON data.
  • Be able to structure your Word Search game for future expansions.
  • Ensure your app is robust, scalable, and maintainable.

๐Ÿ“Œ Step 1: Understanding the JSON Data Structure

The game will fetch words from JSON (or Firebase in the future), structured like this:

json
{
"Spanish": [
{
"AudioName": "Buenos dias",
"Category": "Greetings",
"Definition": "good morning",
"Word": "Buenos dรญas"
},
{
"AudioName": "Gracias",
"Category": "General",
"Definition": "thank you",
"Word": "Gracias"
}
],
"Italian": [
{
"AudioName": "Messaggio",
"Definition": "message",
"Word": "messaggio"
}
]
}

๐Ÿ“Œ Step 2: Create a TypeScript Type for JSON Data

We need to ensure TypeScript correctly recognizes our JSON structure.

๐Ÿ“ Inside src/types.ts, create a type definition:

typescript
export type WordEntry = {
AudioName: string;
Category?: string; // Optional field
Definition: string;
Word: string;
};

export type LanguageData = {
[key: string]: WordEntry[];
};

๐Ÿ” Explanation:

  • WordEntry: Defines the structure of each word object.
    • AudioName (string) โ†’ Stores the wordโ€™s audio file name.
    • Category (optional string ?) โ†’ Groups words by categories.
    • Definition (string) โ†’ English meaning of the word.
    • Word (string) โ†’ The actual word in the selected language.
  • LanguageData: Defines a dictionary where:
    • Each key (Spanish, Italian, etc.) maps to an array of WordEntry objects.

โœ… Now TypeScript knows how to handle our JSON data!


๐Ÿ“Œ Step 3: Create the โ€œStart Gameโ€ Screen (game.tsx)

This screen will list available languages, allowing the user to select one.

๐Ÿ“ Location: app/game.tsx

๐Ÿ”น New game.tsx

typescript
import { View, Text, FlatList, Button, TouchableOpacity } from "react-native";
import { useRouter } from "expo-router";
import { globalStyles } from "@/src/globalStyles";
import jsonData from "@/src/data.json";
import { LanguageData } from "@/src/types";

export default function GameSelection() {
const router = useRouter();
const languages = Object.keys(jsonData as LanguageData); // Extract languages

return (
<View style={globalStyles.container}>
<Text style={globalStyles.title}>Select a Language</Text>
<FlatList
data={languages}
keyExtractor={(item) =>
item}
renderItem={({ item }) => (
<TouchableOpacity
style={globalStyles.button}
onPress={() =>
router.push(`/wordSearch?lang=${item}`)}
>
<Text style={globalStyles.buttonText}>{item}</Text>
</TouchableOpacity>
)}
/>
<Button title="Back" onPress={() => router.back()} color="gray" />
</View>

);
}

๐Ÿ” Explanation:

  • Object.keys(jsonData as LanguageData) โ†’ Extracts the available languages (Spanish, Italian, etc.).
  • FlatList โ†’ Dynamically lists available languages.
  • router.push("/wordSearch?lang=item") โ†’ Passes the selected language to wordSearch.tsx.

โœ… Now users can select a language!


๐Ÿ“Œ Step 4: Implement Word Search (wordSearch.tsx)

This screen will: โœ”๏ธ Retrieve the selected language from the navigation parameter.
โœ”๏ธ Display words at the bottom in three columns.
โœ”๏ธ Use TypeScript to handle JSON data safely.

๐Ÿ“ Location: app/wordSearch.tsx

๐Ÿ”น Updated wordSearch.tsx

typescript
import { View, Text, FlatList, Button } from "react-native";
import { useLocalSearchParams, useRouter } from "expo-router";
import { globalStyles } from "@/src/globalStyles";
import jsonData from "@/src/data.json";
import { LanguageData, WordEntry } from "@/src/types";

export default function WordSearch() {
const { lang } = useLocalSearchParams();
const router = useRouter();

if (!lang || typeof lang !== "string" || !(lang in jsonData)) {
return <Text style={globalStyles.title}>Invalid Language</Text>;
}

const words = (jsonData as LanguageData)[lang].map((item) => item.Word);
const definitions = (jsonData as LanguageData)[lang].map((item) => item.Definition);

return (
<View style={globalStyles.container}>
<Text style={globalStyles.title}>{lang} Words:</Text>

<FlatList
data={words}
keyExtractor={(item) =>
item}
numColumns={3}
renderItem={({ item }) => (
<View style={globalStyles.wordBox}>
<Text>{item}</Text>
</View>
)}
/>

<View style={globalStyles.gridPlaceholder}>
<Text>Word Search Grid Placeholder</Text>
</View>

<View style={globalStyles.buttonContainer}>
<Button title="Options" onPress={() => router.push("/options")} />
<Button title="Back" onPress={() => router.back()} color="gray" />
</View>
</View>
);
}

๐Ÿ” Explanation of Fixes & Changes:

  • useLocalSearchParams() โ†’ Correctly retrieves the language from the URL.
  • typeof lang !== "string" || !(lang in jsonData) โ†’ Ensures lang is valid.
  • Explicit Type Casting (as LanguageData) โ†’ Ensures JSON data matches TypeScript expectations.

โœ… Now the Word Search screen works perfectly with TypeScript!


๐Ÿ“Œ Final Steps

1๏ธโƒฃ Restart the app:

bash
npx expo start

2๏ธโƒฃ Navigate through:

  • Main Menu โ†’ Select a Language โ†’ Word Search
  • Ensure the word list & buttons display correctly. 3๏ธโƒฃ Prepare for building the actual word search grid!

๐Ÿš€ Now we have a structured Word Search game with TypeScript, JSON, and navigation! ๐ŸŽฎ


๐ŸŽฏ Whatโ€™s Next?

In Tutorial #8, we will: โœ”๏ธ Build the actual Word Search grid with randomized letter placement!
โœ”๏ธ Allow users to find words dynamically in the grid.

๐Ÿ”ฅ Let me know if everything is working and if the explanations are clear! ๐Ÿš€