Welcome, Fellow Developers! 🌟

Hey there! Today i'm excited to share my latest venture into the world of mobile development. After much anticipation, I finally took the plunge into React Native, and I can’t wait to tell you all about my journey while building a Calculator App! So grab your favorite drink, settle in, and let’s dive into the world of coding!

Why React Native? 🤔

You might be wondering why I chose React Native for my project. Well, it’s quite simple! The allure of creating a stunning app that runs seamlessly on both iOS and Android was too good to pass up. With React Native, I can write code once and deploy it everywhere. Think about the possibilities! No more juggling multiple codebases or worrying about platform-specific quirks. Plus, the community is buzzing with energy, and the resources available are incredible.

Introducing My Calculator App 💡

Let’s talk about the star of the show—the Calculator App. At first glance, it may seem like a straightforward project, but it’s packed with features that elevate it beyond the basic functionality. Here’s what you can expect:

  • Responsive Design: The app adjusts to different screen sizes, ensuring that whether you’re on a tablet or a phone, it looks fabulous.
  • Dark and Light Themes: Because who doesn’t love a little customization? Users can switch between dark and light themes, making it comfortable to use in any environment.
  • Decimal and Percentage Functions: More than just basic math, this app has your back for those tricky decimal and percentage calculations.

Getting Started with the Code 🔧

If you’re itching to try this out for yourself, here’s how to get started:

  1. Clone the Repository:

    git clone https://github.com/hari7261/calculator-native.git
    cd calculator-native
  2. Install Dependencies:

    npm install
  3. Run the Application: For Expo:

    npx expo start

    For React Native CLI:

    npx react-native run-android
    # or
    npx react-native run-ios

A Peek Under the Hood 💻

Now, let’s take a closer look at the heart of my app—the Calculator.js file. This is where all the magic happens! Here’s a snippet to give you an idea of what it looks like:

import React, { useState } from 'react';
import { View, Text, TouchableOpacity, StyleSheet, SafeAreaView, useColorScheme, Modal, ScrollView } from 'react-native';
 
const App = () => {
  const systemColorScheme = useColorScheme();
  const [darkMode, setDarkMode] = useState(systemColorScheme === 'dark');
  const [display, setDisplay] = useState('0');
  const [currentValue, setCurrentValue] = useState(null);
  const [operator, setOperator] = useState(null);
  const [waitingForOperand, setWaitingForOperand] = useState(false);
  const [history, setHistory] = useState([]);
  const [isHistoryVisible, setIsHistoryVisible] = useState(false);
 
  const toggleTheme = () => {
    setDarkMode(!darkMode);
  };
 
  const inputDigit = (digit) => {
    if (waitingForOperand) {
      setDisplay(String(digit));
      setWaitingForOperand(false);
    } else {
      setDisplay(display === '0' ? String(digit) : display + digit);
    }
  };
 
  const clearDisplay = () => {
    setDisplay('0');
    setCurrentValue(null);
    setOperator(null);
    setWaitingForOperand(false);
  };
 
  const performOperation = (nextOperator) => {
    const inputValue = parseFloat(display);
    if (currentValue == null) {
      setCurrentValue(inputValue);
    } else if (operator) {
      const result = calculate(currentValue, inputValue, operator);
      setDisplay(String(result));
      setHistory([...history, `${currentValue} ${operator} ${inputValue} = ${result}`]);
      setCurrentValue(result);
    }
    setWaitingForOperand(true);
    setOperator(nextOperator);
  };
 
  const calculate = (a, b, op) => {
    switch (op) {
      case '+':
        return a + b;
      case '-':
        return a - b;
      case '×':
        return a * b;
      case '÷':
        return a / b;
      default:
        return b;
    }
  };
 
  return (
    <SafeAreaView style={[styles.container, { backgroundColor: darkMode ? '#1C1C1E' : '#FFFFFF' }]}>
      {/* UI components and more go here */}
    </SafeAreaView>
  );
};
 
const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 20,
  },
  // Additional styles here
});
 
export default App;

Key Features Explained 🔑

  • Input Digit: This function updates the display when you tap a digit. It makes sure you can enter numbers easily without any hiccups.
  • Clear Display: Tapping the clear button resets everything. It’s like hitting the reset button on your day—refreshing!
  • Perform Operation: This is the brain of the calculator, handling the math magic. You can chain operations together seamlessly.
  • Calculate: This function takes care of the heavy lifting, performing the actual arithmetic based on the selected operation.

What’s great about this project is the potential for customization and enhancements. Here are some ideas to take it to the next level:

  • Complex Operations: Want to add more? Consider implementing square roots, exponents, or even a memory function for storing results!
  • Styling Tweaks: Play around with the styles to make the buttons and layout pop. A unique design can make your app stand out.
  • User Experience Enhancements: Think about adding animations or interactive elements to make the app feel even more dynamic and fun.

⚙️ In detailed explaination of the code, lets breakdown.

🌿 Square Root Function

Give your users the ability to calculate square roots with a simple tap. Imagine the convenience of finding the square root without any hassle!

const performSquareRoot = () => {
    const inputValue = parseFloat(display);
    const result = Math.sqrt(inputValue);
    setDisplay(String(result));
    setHistory([...history, `√${inputValue} = ${result}`]);
};

🌌 Exponentiation

Empower your users to raise numbers to any power! Include buttons for or even x^y for versatility.

const performExponentiation = (exponent) => {
    const inputValue = parseFloat(display);
    const result = Math.pow(inputValue, exponent);
    setDisplay(String(result));
    setHistory([...history, `${inputValue} ^ ${exponent} = ${result}`]);
};

🔭 Trigonometric Functions

Add a dash of complexity with sine, cosine, and tangent calculations. Your app will be the go-to for math enthusiasts!

const performTrigonometricFunction = (func) => {
    const inputValue = parseFloat(display);
    let result;
 
    switch (func) {
        case 'sin':
            result = Math.sin(inputValue);
            break;
        case 'cos':
            result = Math.cos(inputValue);
            break;
        case 'tan':
            result = Math.tan(inputValue);
            break;
        default:
            return;
    }
    setDisplay(String(result));
    setHistory([...history, `${func}(${inputValue}) = ${result}`]);
};

💾 Memory Functions

📦 Memory Recall (MR)

Let your users recall stored values effortlessly! This feature is perfect for repeated calculations.

const [memory, setMemory] = useState(0);
 
const recallMemory = () => {
    setDisplay(String(memory));
};

💾 Memory Store (M+)

Allow users to store the current display value in memory with a simple button press.

const storeInMemory = () => {
    setMemory(parseFloat(display));
};

❌ Memory Clear (MC)

Add an option for users to clear the stored memory, keeping their workspace tidy.

const clearMemory = () => {
    setMemory(0);
};

🌈 Enhanced User Experience

🌌 User-defined Constants

Enable users to define constants like π for quick access. It’s a small touch that can make a big difference!

const insertPi = () => {
    setDisplay(String(Math.PI));
};

📜 History Feature

Revamp the history feature to let users click on previous calculations. Imagine them being able to reuse results with just a tap!

const handleHistoryClick = (item) => {
    setDisplay(item.result); // Assume item has a result property
    setIsHistoryVisible(false);
};

⌨️ Keyboard Support

Implement keyboard support for those who prefer typing. It adds a layer of convenience and accessibility!

useEffect(() => {
    const handleKeyPress = (event) => {
        if (event.key >= 0 && event.key <= 9) {
            inputDigit(event.key);
        } else if (event.key === 'Enter') {
            performOperation(operator);
        } // Add more cases for other keys as needed
    };
    window.addEventListener('keydown', handleKeyPress);
    return () => {
        window.removeEventListener('keydown', handleKeyPress);
    };
}, [display, currentValue, operator]);

🌟 Happy coding!