Open In App

Build a Dictionary App Using React Native

Last Updated : 06 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we are going to implement a Dictionary app using React Native. The app allows users to effortlessly search for word meanings, access definitions, listen to pronunciations, and examine example sentences.

Preview of final output: Let us have a look at how the final output will look like.

Build-a-Dictionary-App-Using-React-Native

Prerequisites

Approach:

  • The use-State hook is used to declare and initialize state variables efficiently. These variables, including newWord, che­ckedWord, definition, example, sound, and data, play crucial roles in storing different pieces of information throughout the app’s
  • This function is invoked when the user inputs a word into the search field. It then updates the new word state with the entered word.
  • The getInfo function is triggered when the user clicks the “Search” button. It performs data retrieval from a dictionary API based on the entered word. After retrieving the response, it processes the data and updates the state with comprehensive information about the word, including its definition and an example of its usage.
  • This function enables the user to easily listen to the accurate pronunciation of a word. By checking the availability of audio data, it utilizes the eXPO-AV library to seamlessly load and play the corre­sponding audio.
  • The clear function serves to reset the application’s state variables and unload any previously loaded audio. Furthermore, it effectively removes the results from the previous search, allowing users to initiate a fresh search with ease.

Steps to Create React Native Application

Step 1: Create a React Native Application via following command

npx create-expo-app DictionaryApp

Step 2: Change the directory to the project folder

cd DictionaryApp

Step 3: Install required Library

npm install react-native-vector-icons
expo install expo-av

Project Structure:

The updated dependencies in package.json file will look like

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

Example: In this example we are using the above-explained approach.

Javascript




// App.js
import React, { useState } from 'react';
import { View, Text, TextInput, TouchableOpacity, ScrollView}
    from 'react-native';
import { Audio } from 'expo-av';
import { AntDesign }
    from 'react-native-vector-icons';
import styles from './styles';
 
export default function App() {
    const [newWord, setNewWord] = useState("");
    const [checkedWord, setCheckedWord] = useState("");
    const [definition, setDefinition] = useState("");
    const [example, setExample] = useState("");
    const [sound, setSound] = useState();
    const [data, setData] = useState(null);
    const [error, setError] = useState(null);
 
    const searchWord = (enteredWord) => {
        setNewWord(enteredWord)};
 
    const getInfo = async () => {
        let url =
 
        try {
            const response = await fetch(url);
            const fetchedData = await response.json();
 
            if (response.status === 200) {
                 
                // Successful response
                setData(fetchedData);
 
                let word = fetchedData[0].word;
                setCheckedWord(word);
 
                let def = fetchedData[0]
                    .meanings[0].definitions[0].definition;
                setDefinition(def);
 
                let eg = fetchedData[0]
                    .meanings[0].definitions[0].example;
                setExample(eg);
 
                // Clear any previous error
                setError(null);}
            else {
                 
                // API response indicates an error
                setError("Word not found in the database");
 
                // Automatically clear the error after 3 seconds
                setTimeout(() => {
                    setError(null);}, 3000);}}
        catch (error) {
            console.error('Error fetching data:', error);
            setError("An error occurred while fetching data");
 
            // Automatically clear the error after 3 seconds
            setTimeout(() => {setError(null);}, 3000);}};
 
    const playAudio = async () => {
        if (data && data[0].phonetics && data[0].phonetics[0]
                 && data[0].phonetics[0].audio) {
            if (sound) {
                await sound.unloadAsync()}
 
            const audioUri = data[0].phonetics[0].audio;
 
            const { sound, status } =
                await Audio.Sound.createAsync({ uri: audioUri });
 
            if (status.isLoaded) {
                setSound(sound);
                await sound.playAsync()}}};
 
    const clear = async () => {
        setCheckedWord("");
        setDefinition("");
        setExample("");
        setNewWord("");
 
        if (sound) {
            await sound.unloadAsync()}};
 
    return (
        <View style={styles.container}>
            <Text style={styles.heading}>Dictionary App</Text>
            <View style={styles.inputContainer}>
                <TextInput
                    style={styles.input}
                    placeholder="Search..."
                    onChangeText={(text) => searchWord(text)}/>
                <TouchableOpacity style={styles.button}
                                  onPress={() => getInfo()}>
                    <Text style={styles.buttonText}>Search</Text>
                </TouchableOpacity>
            </View>
            {error && (
                <Text style={styles.errorText}>{error}</Text>)}
            {checkedWord && !error && (
                <ScrollView style={styles.resultsContainer}>
                    <Text style={styles.word}>{checkedWord}</Text>
                    <TouchableOpacity style={styles.playButton}
                                      onPress={() => playAudio()}>
                        <AntDesign name="sound" size={20} color="#ffffff" />
                    </TouchableOpacity>
                    <View style={styles.resultTextContainer}>
                        <Text style={styles.resultText}>
                            Definition: {definition}
                        </Text>
                        <Text style={styles.resultText}>
                            Example: {example}
                        </Text>
                    </View>
                </ScrollView>)}
            <TouchableOpacity style={styles.clearButton}
                              onPress={() => clear()}>
                <Text style={styles.buttonText}>Clear</Text>
            </TouchableOpacity>
        </View>)}


Javascript




// Styles.js
const styles = {
    container: {
        flex: 1,
        alignItems: 'center',
        backgroundColor: '#F5F5F5',
        padding: 20,
    },
    errorText: {
        color: 'red',
        fontSize: 23,
        marginTop: 10,
    },
    heading: {
        fontSize: 30,
        marginBottom: 20,
        fontWeight: 'bold',
        color: '#333',
    },
    inputContainer: {
        flexDirection: 'row',
        alignItems: 'center',
        marginBottom: 20,
        backgroundColor: '#FFF',
        borderRadius: 10,
        shadowColor: 'grey',
        shadowOffset: { width: 0, height: 2 },
        shadowOpacity: 0.2,
        shadowRadius: 3,
        elevation: 3,
    },
    input: {
        flex: 1,
        padding: 15,
        fontSize: 18,
    },
    button: {
        backgroundColor: '#007BFF',
        padding: 15,
        marginLeft: 10,
        borderRadius: 10,
    },
    buttonText: {
        color: '#fff',
        fontWeight: 'bold',
        fontSize: 18,
    },
    resultsContainer: {
        alignItems: 'center',
        backgroundColor: '#FFF',
        borderRadius: 10,
        shadowColor: '#000',
        shadowOffset: { width: 0, height: 2 },
        shadowOpacity: 0.2,
        shadowRadius: 3,
        elevation: 3,
        padding: 20,
        height: 300,
    },
    word: {
        fontSize: 24,
        fontWeight: 'bold',
        marginBottom: 10,
    },
    playButton: {
        backgroundColor: '#2ecc71',
        width: 60,
        height: 60,
        borderRadius: 30,
        alignItems: 'center',
        justifyContent: 'center',
        marginTop: 20,
    },
    playButtonText: {
        color: '#fff',
        fontSize: 20,
        fontWeight: 'bold',
    },
    resultTextContainer: {
        alignItems: 'center',
        paddingTop: 20,
    },
    resultText: {
        fontSize: 18,
        marginBottom: 10,
    },
    clearButton: {
        backgroundColor: '#FF4A4A',
        padding: 15,
        marginTop: 20,
        borderRadius: 10,
    },
    clearButtonText: {
        color: '#fff',
        fontWeight: 'bold',
        fontSize: 18,
    },
};
export default styles;


Steps to run your application

Step 1: To run react native application use the following command:

npx expo start

Step 2: Please execute command according to your machine.

  • To run on Android:
npx react-native run-android

  • To run on iOS:
npx react-native run-ios

Output:

Build-a-Dictionary-App-Using-React-Native



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads