Submitted over 2 years ago
Tip Calculator App built with ReactJS including input validation
@chowjiaming
Design comparison
SolutionDesign
Solution retrospective
I was having some issues with displaying and resetting the input field value for the custom tip input button. It would display the currently calculated tip percentage if the user were to click back onto one of the default value offerings. One solution I found was to have a separate state to display as value concurrently with the actual calculated tip percentage. This custom tip percentage value would be nulled out as soon as the calculated tip value changed back to default.
const handleClick = (e) => {
setInputData((prevState) => ({
...prevState,
tipPercentage: parseInt(e.target.id),
customTipPercentage: null,
tipPercentageError: false,
}));
};
const handleCustomTip = (e) => {
const re = /^[1-9]$|^[1-9][0-9]$|^(100)$/;
if (!e.target.value) {
setInputData((prevState) => ({
...prevState,
tipPercentage: 0,
customTipPercentage: 0,
}));
} else if (!re.test(e.target.value)) {
setInputData((prevState) => ({
...prevState,
tipPercentageError: true,
}));
e.target.value = inputData.tipPercentage;
} else {
setInputData((prevState) => ({
...prevState,
tipPercentage: e.target.value,
customTipPercentage: e.target.value,
tipPercentageError: false,
}));
}
};
Community feedback
Please log in to post a comment
Log in with GitHubJoin our Discord community
Join thousands of Frontend Mentor community members taking the challenges, sharing resources, helping each other, and chatting about all things front-end!
Join our Discord