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 app 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 React, { useState } from "react";
export default function App() {
const [percentageTip, setPercentageTip] = useState(0);
const [billAmount, setBillAmount] = useState(0);
const [tipAmount, setTipAmount] = useState(0);
const [total, setTotal] = useState(0);
const calculate = (e) => {
e.preventDefault();
const formValid = +billAmount > 0 && +percentageTip > 0;
if (!formValid) {
return;
}
const tipAmount = +billAmount * (+percentageTip / 100);
const total = +billAmount * (1 + percentageTip / 100);
setTipAmount(tipAmount);
setTotal(total);
};
return (
<div className="App">
<form onSubmit={calculate}>
<div>
<label>bill amount</label>
<input
value={billAmount}
onChange={(e) => setBillAmount(e.target.value)}
/>
</div>
<div>
<label>percentage tip</label>
<input
value={percentageTip}
onChange={(e) => setPercentageTip(e.target.value)}
/>
</div>
<button type="submit">calculate</button>
</form>
<p>tip amount: {tipAmount.toFixed(2)}</p>
<p>total: {total.toFixed(2)}</p>
</div>
);
}
We have the percentageTip , billAmount , tipAmount , and total states in the App component.
We create them with the useState hook.
Then we define the calculate function.
We call e.preventDefault() to do client-side form submission.
Then we check billAmoubnt and percentageTip to see if they’re valid values.
If they are, then we calculate the tipAmount and total .
And we call setTipAmount and setTotal to set the values.
Below that, we have the form element with the onSubmit prop set to calculate so that it runs when we click the calculate button.
In the form, we have inputs to let us enter the bill amount and percentage tip.
value has the value from the states.
And we set the states with the function we pass into the onChange prop.
e.target.value gets the inputted value.
Below that, we display the tipAmount and total .
toFixed lets us round the numbers to the given amount of decimal places.
Conclusion
We can create a tip calculator easily with React and JavaScript.