This Banner is For Sale !!
Get your ad here for a week in 20$ only and get upto 15k traffic Daily!!!

React Native Speed Math App


Howdy Everybody, I am again after 1 yr and 4 months.This time with react native venture.

Let’s begin the venture
I created this venture with Expo and used used Expo Router for routing.
Create a brand new folder and open the terminal and run this command

npx create-expo-app@newest
Enter fullscreen mode

Exit fullscreen mode

After operating this command efficiently, You may take away the boilerplate code and begin recent with a brand new venture. Run the next command to reset your venture:

npm run reset-venture
Enter fullscreen mode

Exit fullscreen mode

Earlier than leaping to the code, let’s perceive the performance of our app.
When the consumer is on dwelling display then the consumer has to decide on one mathematical operation that they wish to follow.

Home Screen

As soon as they choose the operation then they’re moved to the Quiz Display and questions will begin showing on the consumer display. The consumer should reply the query inside 10sec and if the reply is appropriate then the rating is elevated by 1 and the following query will seem and if the consumer doesn’t reply the query inside 10sec then the following query will probably be rendered.

Quiz Screen

app is the start line of our software and inside app, _layout.tsx is our root format and index.tsx is our dwelling web page.



_layout.tsx :-

import { Stack } from "expo-router";

export default operate RootLayout() {
  return (
    <Stack>
      <Stack.Display identify="index" choices={{headerShown:false}}/>
      <Stack.Display identify="quiz/[id]"choices={{headerShown:false}}/>
    </Stack>
  );
}

Enter fullscreen mode

Exit fullscreen mode

Now we have now two screens, one the house display and the opposite will probably be a dynamic display which can render the questions primarily based on the operation chosen by the consumer.



index.tsx :-

// HomeScreen.js
import React, { useState } from 'react';
import { View, Textual content, Button, StyleSheet } from 'react-native';
import {router} from 'expo-router'

const HomeScreen = () => {

  const handleStartQuiz = (operation: string) => {
    router.push({pathname:'/quiz/[id]',
    params:{id:operation}

    }

    )
  };

  return (
    <View fashion={kinds.container}>
      <Textual content fashion={kinds.title}>Select a Operation:</Textual content>
      <Button title="Addition" onPress={() => handleStartQuiz('addition')} />
      <Button title="Subtraction" onPress={() => handleStartQuiz('subtraction')} />
      <Button title="Multiplication" onPress={() => handleStartQuiz('multiplication')} />
      <Button title="Division" onPress={() => handleStartQuiz('division')} />
    </View>
  );
};

const kinds = StyleSheet.create({
  container: {
    show:'flex',
    marginTop:60,
    justifyContent: 'heart',
    // alignItems: 'heart',
    rowGap:10,
    margin:20
  },
  title: {
    fontSize: 20,
    marginTop: 20,
  },
});

export default HomeScreen;
Enter fullscreen mode

Exit fullscreen mode

Now create a brand new folder app/quiz and within it create a dynamic route [id].tsx



[id].tsx :-

// QuizScreen.js
import { useLocalSearchParams } from 'expo-router';
import React, { useState, useEffect } from 'react';
import { View, Textual content, TextInput, StyleSheet, SafeAreaView } from 'react-native';

const QuizScreen = () => {
    const { id } = useLocalSearchParams<{id:string}>();
    const operation = typeof id === 'string' ? id : 'addition'; // Present a default operation if id is undefined or not a string
    const [num1, setNum1] = useState(0);
    const [num2, setNum2] = useState(0);
    const [userAnswer, setUserAnswer] = useState('');
    const [score, setScore] = useState(0);
    const [time, setTime] = useState(10);

    useEffect(() => {
        console.log('Operation from params:', operation);
        generateQuestion();
    }, [operation]);

    const generateQuestion = () => {
        change (operation) {
            case 'addition':
                setNum1(Math.ground(Math.random() * 100) + 1);
                setNum2(Math.ground(Math.random() * 100) + 1);
                break;
            case 'subtraction':
                setNum2(Math.ground(Math.random() * 100) + 1);
                setNum1(Math.ground(Math.random() * 100) + 1); // Adjusted to make sure num2 is generated correctly
                break;
            case 'multiplication':
                setNum1(Math.ground(Math.random() * 100) + 1);
                setNum2(Math.ground(Math.random() * 10) + 1);
                break;
            case 'division':
                const divisor = Math.ground(Math.random() * 9) + 1;
                const quotient = Math.ground(Math.random() * 100) + 1;
                setNum2(divisor);
                setNum1(divisor * quotient);
                break;
            default:
                setNum1(0);
                setNum2(0);
        }
    };

    const handleAnswerChange = (textual content:string) => {
        setUserAnswer(textual content);
        const reply = calculateAnswer();
        const tolerance = 0.0001; // Regulate tolerance stage as wanted
        if (Math.abs(parseFloat(textual content) - reply) <= tolerance) {
            setScore(rating + 1);
            handleNextQuestion();
        }
    };

    const calculateAnswer = () => {
        change (operation) {
            case 'addition':
                return num1 + num2;
            case 'subtraction':
                return num1 - num2;
            case 'multiplication':
                return num1 * num2;
            case 'division':
                return num1 / num2; // Guarantee it is a exact division
            default:
                return num1 + num2; // Default to addition
        }
    };

    const handleNextQuestion = () => {
        generateQuestion();
        setUserAnswer('');
        setTime(10);
    };

    useEffect(() => {
        const timer = setInterval(() => {
            setTime((prevTime) => {
                if (prevTime > 0) {
                    return prevTime - 1;
                } else {
                    handleNextQuestion();
                    return 10; // Reset timer to 10 seconds for the following query
                }
            });
        }, 1000);

        return () => clearInterval(timer);
    }, []);

    return (
        <SafeAreaView fashion={kinds.container}>
            <Textual content fashion={{ fontWeight: 'daring', fontSize: 38 }}>Velocity Math</Textual content>
            <View fashion={kinds.topBar}>
                <View>
                    <Textual content fashion={kinds.timer}><Textual content></Textual content> {time} sec</Textual content>
                </View>
                <Textual content fashion={kinds.rating}>Rating: {rating}</Textual content>
            </View>
            <Textual content fashion={kinds.query}>
                {num1} {getOperationSymbol(operation)} {num2} =
            </Textual content>
            <TextInput
                fashion={kinds.enter}
                keyboardType="numeric"
                worth={userAnswer}
                onChangeText={handleAnswerChange}
                autoFocus={true}
            />
        </SafeAreaView>
    );
};

const getOperationSymbol = (operation:string) => {
    change (operation) {
        case 'addition':
            return '+';
        case 'subtraction':
            return '-';
        case 'multiplication':
            return '×';
        case 'division':
            return '÷';
        default:
            return '+';
    }
};

const kinds = StyleSheet.create({
    container: {
        marginTop:50,
        flex: 1,
        alignItems: 'heart',
    },
    query: {
        fontSize: 20,
        marginTop: 200,
        marginBottom: 10,
    },
    enter: {
        top: 40,
        borderColor: 'grey',
        borderWidth: 1,
        marginBottom: 20,
        textAlign: 'heart',
        width: 100,
    },
    timer: {
        marginTop: 10,
        fontSize: 16,
        fontWeight: 'daring',
    },
    rating: {
        marginTop: 10,
        fontSize: 16,
        fontWeight: 'daring',
    },
    topBar: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        hole: 30,
        alignItems: 'heart',
        width: 360,
    },
});

export default QuizScreen;

Enter fullscreen mode

Exit fullscreen mode

*Necessary factors *

  • Right here,useLocalSearchParams from expo-router is used to extract question parameters from the URL.
  • useLocalSearchParams extracts the id parameter from the URL, which determines the kind of arithmetic operation.
  • operation units the operation kind primarily based on id or defaults to “addition”.
  • We initialize state variables: num1, num2, userAnswer, rating, and time.

Perform to Generate Questions

    const generateQuestion = () => {
        change (operation) {
            case 'addition':
                setNum1(Math.ground(Math.random() * 100) + 1);
                setNum2(Math.ground(Math.random() * 100) + 1);
                break;
            case 'subtraction':
                setNum2(Math.ground(Math.random() * 100) + 1);
                setNum1(Math.ground(Math.random() * 100) + 1);
                break;
            case 'multiplication':
                setNum1(Math.ground(Math.random() * 100) + 1);
                setNum2(Math.ground(Math.random() * 10) + 1);
                break;
            case 'division':
                const divisor = Math.ground(Math.random() * 9) + 1;
                const quotient = Math.ground(Math.random() * 100) + 1;
                setNum2(divisor);
                setNum1(divisor * quotient);
                break;
            default:
                setNum1(0);
                setNum2(0);
        }
    };
Enter fullscreen mode

Exit fullscreen mode

I am new to react native and possibly not that good at explaining the code. Nonetheless, you may attain out to me
LinkedIn
Live Apk
Code

The Article was Inspired from tech community site.
Contact us if this is inspired from your article and we will give you credit for it for serving the community.

This Banner is For Sale !!
Get your ad here for a week in 20$ only and get upto 10k Tech related traffic daily !!!

Leave a Reply

Your email address will not be published. Required fields are marked *

Want to Contribute to us or want to have 15k+ Audience read your Article ? Or Just want to make a strong Backlink?