Photo by Sam Dan Truong on Unsplash

React is an easy to use JavaScript framework that lets us create front end apps.

In this article, we’ll look at how to create a tip calculator with React and JavaScript.

Create the Project

We can create the React project with Create React App.

To install it, we run:

npx create-react-app tip-calculator

with NPM to create our React project.

Create the Tip Calculator App

To create the tip calculator app, we write:

import { useState } from "react";
export default function App() {
const [subtotal, setSubtotal] = useState(0);
const [numDiners, setNumDiners] = useState(0);
const [tipPercentage, setTipPercetnage] = useState(0);
const [result, setResult] = useState({});
  const submit = (e) => {
if (+subtotal <= 0 || +numDiners <= 0 || +tipPercentage <= 0) {
const total = +subtotal * (1 + +tipPercentage);
setResult({ total, totalPerDiner: +total / +numDiners });
  return (
<div className="App">
<form onSubmit={submit}>
onChange={(e) => setSubtotal(}
<label>number of people sharing the bill</label>
onChange={(e) => setNumDiners(}
<label>tip percentage</label>
onChange={(e) => setTipPercetnage(}
<option value="0">0%</option>
<option value="0.05">5%</option>
<option value="0.1">10%</option>
<option value="0.15">15%</option>
<option value="0.2">20%</option>
        <button type="submit">Calculate</button>
<p>total: { &&}</p>
total per diner:{" "}
{result.totalPerDiner && result.totalPerDiner.toFixed(2)}

We have the subtotal , numDiners , tipPercentage , and result states.

subtotal is the subtotal.

numDiners is the number of diners.

tipPercentage has the tip percentage between 0 and 100.

In the submit function, we call e.preventDefault() to prevent server-side form submission.

Then we check if the values are valid with the if block.

Then we compute the total and the result object and call setResult to set it.

In the return statement, we have the input fields with the value and onChange properties to get and set the values respectively.

We get the value from .

The form has the onSubmit prop to set the submit event listener.

Below that, we have the result data displayed.


We can create a tip calculator with React and JavaScript.

More content at

Create a Tip Calculator with React and JavaScript was originally published in JavaScript in Plain English on Medium, where people are continuing the conversation by highlighting and responding to this story.