DEV Community

Usama
Usama

Posted on

💻 Building a Simple Tip Calculator in React: A Challenge

As part of my React course, I took on a small coding challenge: building a tip calculator. This project might look simple, but it’s a great way to understand React state management, controlled inputs, and real-time calculations.

What the app does:

  • Lets the user enter a bill amount.
  • Allows selecting tip percentages separately for yourself and a friend.
  • Dynamically calculates each tip, the average tip, and the total bill.
  • Provides a reset button to start over anytime.

Core Concept:

Instead of hardcoding values, the app uses state variables to keep track of:

const [bill, setBill] = useState(100);
const [yourTipPercent, setYourTipPercent] = useState(5);
const [friendTipPercent, setFriendTipPercent] = useState(10);
Enter fullscreen mode Exit fullscreen mode

When the user selects tips, we calculate:

const yourTip = (bill * yourTipPercent) / 100;
const friendTip = (bill * friendTipPercent) / 100;
const total = bill + yourTip + friendTip;
Enter fullscreen mode Exit fullscreen mode

Interactive Inputs:

React’s controlled components allow us to update the state instantly:

<input type="number" value={bill} onChange={(e) => setBill(Number(e.target.value))} />

<select onChange={(e) => setYourTipPercent(Number(e.target.value))}>
  <option value={0}>0%</option>
  <option value={5}>5%</option>
  <option value={10}>10%</option>
  <option value={20}>20%</option>
</select>
Enter fullscreen mode Exit fullscreen mode

This approach makes the UI dynamic and responsive. As soon as the user changes a value, the total updates instantly.

Takeaways:

  • Using state and controlled inputs is crucial for dynamic React apps.
  • Small challenges like this are perfect to practice arithmetic calculations in React.
  • Even simple projects can teach you good habits for building interactive components.

Top comments (0)