'Dividing an Input field value in React
I have been trying to calculate an input field value, It is a blockchain project. I want the users to input a certain value or worth of a coin they want to purchase and the system to automatically calculate the amount in Ethereum. For Example when a user input 50000, the system should divide the amount by 10000 and the user will pay 5 Eth.
const handleSubmit = (e) => {
const { addressTo, amount, message } = formData;
e.preventDefault();
if ( !amount || !message) return;
sendTransaction();
};
<Input placeholder="Address To" name="addressTo" type="hidden" handleChange={handleChange} />
<Input placeholder="Amount (Coin)" name="amount" type="number" handleChange={handleChange} />
<Input placeholder="Enter Description" name="message" type="text" handleChange={handleChange} />
await ethereum.request({
method: "eth_sendTransaction",
params: [{
from: currentAccount,
to: addressTo,
gas: "0x5208",
value: parsedAmount._hex,
}],
});
Solution 1:[1]
export default function App() {
let formData = {};
const handleSubmit = (e) => {
const { addressTo, amount, message } = formData;
e.preventDefault();
if ( !amount || !message) return;
sendTransaction(formData);
};
const handleChange = (e) => {
let key = e.target.name;
formData[key] =key === 'amount'?e.target.value/10000: e.target.value ;
console.log(formData);
};
const sendTransaction = async (param) => {
await ethereum.request({
method: "eth_sendTransaction",
params: [{
from: param.currentAccount,
to: param.addressTo,
gas: "0x5208",
value: param.parsedAmount._hex,
}],
});
};
return (
<div className="App">
<form onSubmit={handleSubmit}>
<input placeholder="Address To" name="addressTo" type="hidden" onChange={handleChange} />
<input placeholder="Amount (Coin)" name="amount" type="number" onChange={handleChange} />
<input placeholder="Enter Description" name="message" type="text" onChange={handleChange} />
</form>
</div>
);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Nilesh Mishra |
