Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • NextJS
  • Material UI
  • React Bootstrap
  • React Suite
  • Ant Design
  • Reactstrap
  • BlueprintJS
  • React Desktop
  • React Native
  • React Rebass
  • React Spring
  • React Evergreen
  • ReactJS
  • ReactJS
  • JS Formatter
  • Web Technology
Open In App
Next Article:
Create a BMI Calculator App using React-Native
Next article icon

Create a Tip Calculator using React-Native

Last Updated : 23 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

A Tip Calculator proves to be a convenient tool for effortlessly calculating tips and dividing bills among friends at restaurants. The app enables users to input the bill amount, select their desired tip perce­ntage, specify the numbe­r of people sharing the bill, and promptly obtain calculate­d values for both the tip and total amounts

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

Create-a-Tip-Calculator-using-React-Native

Prerequisites:

  • Introduction to React Native
  • React Native Components
  • React Hooks
  • Node.js and npm (Node Package Manager)

Steps to Create React Native Application:

Step 1: Create a react native application by using this command

npx create-react-native-app TipCalculator

Step 2: After creating your project folder, i.e. TipCalculator, use the following command to navigate to it:

cd TipCalculator

Approach :

  • We are using the useState hook to manage the state of various input fields and calculated values.
  • Functions such as handleBillAmountChange­, handleCustomTipChange, handleNumbe­rOfPeopleChange, and handle­TipButtonClick were create­d to effectively manage­ input changes and update rele­vant state variables
  • The calculate­Bill function performs the computation of the tip amount, total bill, and individual share­s based on the provided input value­s.
  • The UI layout in this conte­xt is constructed by utilizing a ScrollView alongside various Vie­w components. Label display and input fields are­ facilitated through the utilization of Text and Te­xtInput components.

Project Structure:


Screenshot-(196)
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"
}

Example: In this example, we'll use react native to to build a Tip calculator.

JavaScript
// App.js   import React, { useState } from 'react';  import { View, Text, TextInput, TouchableOpacity, ScrollView } from 'react-native';  import { styles } from "./styles";   export default function BillSplitter() {  const [billAmount, setBillAmount] = useState('');  const [customTip, setCustomTip] = useState('');  const [numberOfPeople, setNumberOfPeople] = useState('');  const [tipPercentage, setTipPercentage] = useState(0);  const [tipAmount, setTipAmount] = useState('');  const [totalBill, setTotalBill] = useState('');  const [eachPersonBill, setEachPersonBill] = useState('');   const handleBillAmountChange = (value) => {  	const amount = parseFloat(value);   	if (!isNaN(amount) && amount >= 0) {  	setBillAmount(amount.toFixed(2));  	setCustomTip('');  	setTipPercentage(0);  	setTipAmount('');  	setTotalBill('');  	setEachPersonBill('');  	} else {  	// Handle negative or invalid input  	setBillAmount('');  	}  };   const handleCustomTipChange = (value) => {  	const custom = parseFloat(value);   	if (!isNaN(custom) && custom >= 0) {  	setCustomTip(custom.toString());  	setTipPercentage(custom);  	setTipAmount('');  	setTotalBill('');  	setEachPersonBill('');  	} else {  	// Handle negative or invalid input  	setCustomTip('');  	}  };   const handleNumberOfPeopleChange = (value) => {  	const people = parseInt(value);   	if (!isNaN(people) && people >= 0) {  	setNumberOfPeople(people);  	} else {  	// Handle negative or invalid input  	setNumberOfPeople('');  	}  };   const handleTipButtonClick = (percentage) => {  	setTipPercentage(percentage);  	setCustomTip(percentage.toString()); // Set the custom tip input to the selected percentage  };   const calculateBill = () => {  	const bill = parseFloat(billAmount);  	const tip = (bill * tipPercentage) / 100;  	const total = bill + tip;  	const eachPerson = total / parseFloat(numberOfPeople);   	setTipAmount(`₹${tip.toFixed(2)}`);  	setTotalBill(`₹${total.toFixed(2)}`);  	setEachPersonBill(`₹${eachPerson.toFixed(2)}`);  };   return (  	<ScrollView contentContainerStyle={styles.container}>  	<View style={styles.billInput}>  		<Text style={styles.text} >Bill</Text>  		<View style={styles.inputContainer}>  		<Text >₹</Text>  		<TextInput  			style={styles.input}  			keyboardType="numeric" 			value={billAmount}  			onChangeText={handleBillAmountChange}  		/>  		</View>  		<Text style={styles.text} >Select Tip</Text>  		<View style={styles.tipContainer}>  		<TouchableOpacity  			style={[styles.tip, tipPercentage === 5 ? styles.selected : null]}  			onPress={() => handleTipButtonClick(5)}  		>  			<Text style={styles.tipText} >5%</Text>  		</TouchableOpacity>  		<TouchableOpacity  			style={[styles.tip, tipPercentage === 10 ? styles.selected : null]}  			onPress={() => handleTipButtonClick(10)}  		>  			<Text style={styles.tipText}>10%</Text>  		</TouchableOpacity>  		<TouchableOpacity  			style={[styles.tip, tipPercentage === 15 ? styles.selected : null]}  			onPress={() => handleTipButtonClick(15)}  		>  			<Text style={styles.tipText}>15%</Text>  		</TouchableOpacity>  		<TouchableOpacity  			style={[styles.tip, tipPercentage === 25 ? styles.selected : null]}  			onPress={() => handleTipButtonClick(25)}  		>  			<Text style={styles.tipText}>25%</Text>  		</TouchableOpacity>  		<TouchableOpacity  			style={[styles.tip, tipPercentage === 50 ? styles.selected : null]}  			onPress={() => handleTipButtonClick(50)}  		>  			<Text style={styles.tipText}>50%</Text>  		</TouchableOpacity>  		<TouchableOpacity  			style={[styles.tip, tipPercentage === 75 ? styles.selected : null]}  			onPress={() => handleTipButtonClick(75)}  		>  			<Text style={styles.tipText}>75%</Text>  		</TouchableOpacity>  		</View>  		<TextInput  		style={styles.customTip}  		placeholder="Custom Tip in Percentage" 		keyboardType="numeric" 		value={customTip}  		onChangeText={handleCustomTipChange}  		/>  		<Text style={styles.text} >Number of People</Text>  		<TextInput  		style={styles.numberOfPeople}  		placeholder="Number of people" 		keyboardType="numeric" 		value={numberOfPeople}  		onChangeText={handleNumberOfPeopleChange}  		/>  		<TouchableOpacity  		style={styles.generateBillBtn}  		onPress={calculateBill}  		disabled={!billAmount || !numberOfPeople || !tipPercentage}  		>  		<Text style={styles.generateBillBtnText}>Generate Bill</Text>  		</TouchableOpacity>  	</View>  	<View style={styles.billOutput}>  		<Text style={styles.tipAmount}>  		Tip amount <Text style={styles.value}>{tipAmount}</Text>  		</Text>  		<Text style={styles.total}>  		Total <Text style={styles.value}>{totalBill}</Text>  		</Text>  		<Text style={styles.eachPersonBill}>  		Each Person Bill <Text style={styles.value}>{eachPersonBill}</Text>  		</Text>  		<TouchableOpacity  		style={styles.resetBtn}  		onPress={() => handleBillAmountChange('')}  		disabled={!billAmount}  		>  		<Text style={styles.resetBtnText}>Reset</Text>  		</TouchableOpacity>  	</View>  	</ScrollView>  );  }  
JavaScript
// index.js   import { StyleSheet } from 'react-native';   const styles = StyleSheet.create({   container: {  	flex: 1,  	padding: 20,  	backgroundColor: '#fff',  },  billInput: {  	marginBottom: 20,  },  text:{  	fontSize: 16,  	fontWeight: 'bold',  	paddingLeft:10,  },  inputContainer: {  	flexDirection: 'row',  	alignItems: 'center',  },  input: {  	flex: 1,  	borderColor: '#ccc',  	borderWidth: 1,  	padding: 10,  	borderRadius: 4,  	fontSize: 20,  	marginVertical: 10,  },  tipContainer: {  	flexDirection: 'row',  	flexWrap: 'wrap',  	justifyContent: 'space-between',  	marginBottom: 12,  },  tip: {  	width: '30%',  	backgroundColor: '#2395e2',  	borderRadius: 5,  	textAlign: 'center',  	padding: 10,  	marginVertical: 5,  },  selected: {  	backgroundColor: 'green',  },  customTip: {  	borderColor: '#ccc',  	borderWidth: 1,  	padding: 10,  	borderRadius: 4,  	fontSize: 16,  	marginVertical: 10,  },  numberOfPeople: {  	borderColor: '#ccc',  	borderWidth: 1,  	padding: 10,  	borderRadius: 4,  	fontSize: 16,  	marginVertical: 10,  },  generateBillBtn: {  	width: '100%',  	height: 40,  	backgroundColor: '#2395e2',  	borderRadius: 7,  	alignItems: 'center',  	justifyContent: 'center',  	marginVertical: 16,  },  generateBillBtnText: {  	color: 'white',  	fontSize: 16,  	fontWeight: 'bold',  },  billOutput: {  	marginVertical: 15,  	padding: 20,  	backgroundColor: '#2395e2',  	borderRadius: 8,  	color: 'white',  },  tipAmount: {  	marginBottom: 10,  	color:"white",  	fontWeight:"bold",  },  tipText:{  	color:"white",  	fontWeight:"bold",  },  total: {  	marginBottom: 10,  	color:"white",  	fontWeight:"bold",  },  value:{  	color:"white",  	fontWeight:"bold",  	paddingLeft:10,  	fontSize: 19,  },  eachPersonBill:{  	color:"white",  	fontWeight:"bold",  },  resetBtn: {  	padding: 12,  	borderRadius: 5,  	backgroundColor: 'red',  	alignItems: 'center',  	justifyContent: 'center',  	marginTop: 10,  },  resetBtnText: {  	color: 'white',  	fontSize: 16,  	fontWeight: 'bold',  },  	 });   export { styles } 

Steps to Run the application:

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

npx expo start

Step 2: Depending on your Operating System type the following command.

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

Output:


Next Article
Create a BMI Calculator App using React-Native
author
saurabhkumarsharma05
Improve
Article Tags :
  • Web Technologies
  • Geeks Premier League
  • React-Native
  • Geeks Premier League 2023

Similar Reads

  • Create a Scientific Calculator using React-Native
    In this article, we are going to create a scientific calculator using React Native. A scientific calculator is a type of calculator specifically designed to perform complex mathematical, scientific, and engineering calculations. It goes beyond basic arithmetic and includes functions such as trigonom
    2 min read
  • Create a GPA Calculator using React Native
    A GPA calculator proves to be a useful tool for students who want to monitor their academic progress. In this article, we will build a GPA calculator using React Native, a popular framework for building mobile applications. Preview Image PrerequisitesIntroduction to React NativeReact Native Componen
    5 min read
  • Create a BMI Calculator App using React-Native
    In this article, we will create a BMI (Body Mass Index) calculator using React Native. A BMI calculator serves as a valuable and straightforward tool for estimating body fat by considering height and weight measurements.A BMI Calculator App built with React Native allows users to input their age, he
    4 min read
  • Create an Age Calculator App using React-Native
    In this article we are going to implement a Age calculator using React Native. An age calculator app in React Native is a simple application that calculates a person's age based on their birth date and the current date. It's a simple utility designed to determine how many years, months, and days hav
    3 min read
  • Create a Chatbot App using React-Native
    Creating a chatbot app using React Native will be an exciting project. In this article, we are going to implement a Chatbot App using React Native. Chatbot App is a mobile application that answers the user's questions on the basis of their previous learning or content provided by developers. It help
    4 min read
  • Create a Camera App using React-Native
    A camera app using react native is a mobile application that is designed to capture photos or videos using the built-in camera functionality of a mobile device. In this article, you will learn how you can create a camera app with simple steps. Output Preview: Let us have a look at how the final appl
    3 min read
  • Create a Blog App using React-Native
    This article shows how to create a basic blog app using react native. This app contains functionalities such as adding a blog and a delete button to remove the blogs using react native. The user can enter content with a title and then click on 'Add New Post' to create a new blog post Preview of fina
    4 min read
  • Create ClassRoom App using React-Native
    ClassRoom App using React Native is a simple application designed to facilitate online learning and classroom management. These apps are commonly used in educational institutions, schools, colleges, and universities to enhance the teaching and learning experience. Preview of final output: Let us hav
    7 min read
  • Build a Calculator using React Native
    React Native is a well-known technology for developing mobile apps that can run across many platforms. It enables the creation of native mobile apps for iOS and Android from a single codebase. React Native makes it simple to construct vibrant, engaging, and high-performing mobile apps. In this tutor
    6 min read
  • Create a Book Store using React-Native
    React-Native is a flexible frameworks for building mobile applications. We will develop a Book Store application, which allows users to search for a specific book, and store the book in the application. If the user wants to remove the book from the stored list, they can easily remove it by navigatin
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences