Handling Form Data on Button Click in React
In the previous lesson we made it so that when you enter a character into the input in a paragraph, the result would instantly appear. This, of course, looks nice, but it has a drawback.
Let's imagine that we need to do some "heavy", resource-intensive operation. It is not very optimal to do it for each character input - it is better to wait for the final input of data and then perform the required operation once and output the result to a paragraph.
To do this, we need to enter a button, which when pressed will perform our resource-intensive operation. In this case, each input will again have its own state, plus we need another state to record the result of the operation and display it on the screen.
Let's look at an example. Let's say we have two inputs and a button. When the button is pressed, let's find the sum of the numbers entered into the inputs.
We implement:
function App() {
const [value1, setValue1] = useState(0);
const [value2, setValue2] = useState(0);
const [result, setResult] = useState(0);
function handleChange1(event) {
setValue1(event.target.value);
}
function handleChange2(event) {
setValue2(event.target.value);
}
function handleClick() {
setResult(Number(value1) + Number(value2));
}
return <div>
<input value={value1} onChange={handleChange1} />
<input value={value2} onChange={handleChange2} />
<button onClick={handleClick}>btn</button>
<p>result: {result}</p>
</div>;
}
You can use the shortened version:
function App() {
const [value1, setValue1] = useState(0);
const [value2, setValue2] = useState(0);
const [result, setResult] = useState(0);
return <div>
<input value={value1} onChange={event => setValue1(event.target.value)} />
<input value={value2} onChange={event => setValue2(event.target.value)} />
<button onClick={() => setResult(Number(value1) + Number(value2))}>btn</button>
<p>result: {result}</p>
</div>;
}
There are two inputs, two buttons and a paragraph. Let numbers be entered into the inputs. Find the sum of the numbers by pressing the first button, and the product by pressing the second button. Output the result into the paragraph.
There are two inputs, a button and a paragraph. Let the inputs contain dates in the format 2025-12-31. When you click the button, find the difference between the dates in days and output the result to the paragraph.
Modify the previous task so that the current date is the default in the inputs.
Given an input and a paragraph. A number is entered into the input. After losing focus, output the sum of the digits of the entered number into the paragraph.
Given an input and a paragraph. A number is entered into the input. After losing focus, output the product of the divisors of the entered number into the paragraph.