Reputation: 11981
How can I pass currentBook, currentUnits and calculated total
during on click on the Record button
Now it just displays the entered value under the purchased book section. I would like to display the data and calculated amount during on click on Record button. Could someone please advise
ie Amount = units * price
for example it should display following result 1. Mathematics 6 300
https://codesandbox.io/s/falling-grass-gwpf9?file=/src/App.js
function App() {
const [currentBook, setCurrentBook] = useState('')
const [currentUnits, setCurrentUnits] = useState('')
const [currentPrice, setCurrentPrice] = useState('')
const [currentRecord, setCurrentRecord] = useState({book:'', units:'', price:''});
const changeBook = (newBook) => {
setCurrentBook(newBook);
}
const changeUnits = (newunits) => {
setCurrentUnits(newunits);
}
const changePrice = (newprice) => {
setCurrentPrice(newprice);
}
const calculateTotal = (e) => {
var cal_total = currentUnits * currentPrice;
setCurrentRecord(currentBook, currentUnits, cal_total );
//setCurrentRecord({ ...currentRecord, [e.target.name]: e.target.value });
}
return (
<div className="App">
<div>
<h1>Online Shopping</h1>
</div>
<div className="flexbox-container">
<div className="maintransaction">
<h3>Choose a book</h3>
<div className="container">
<select defaultValue={'DEFAULT'} onChange={(event) => changeBook(event.target.value)}>
<option value="DEFAULT" disabled>Choose a book ...</option>
<option value="maths">Mathematics</option>
<option value="science">Science</option>
<option value="english">English</option>
<option value="German">German</option>
</select>
</div><br></br>
<div className="quantity">
<span className="units">
<label>Units</label>
<input name="units" type="text" onChange={(event) => changeUnits(event.target.value)}></input>
</span>
<span className="price">
<label>Price</label>
<input name="price" type="text" onChange={(event) => changePrice(event.target.value)}></input>
</span>
</div>
<div className="recordBtn">
<button onClick={(event) => calculateTotal()}>Record</button>
</div>
</div>
<div className="purchasedbooks">
<h3>Purchased book:</h3>
<table>
<tr>
<th>Item no</th>
<th>Books</th>
<th>Units</th>
<th>Price</th>
</tr>
{
//currentRecord.map(({ currentBook, currentUnits }) => (
<tr>
<td>1.</td>
<td>{currentBook}</td>
<td>10</td>
<td>250</td>
</tr>
// ))
}
</table>
</div>
</div>
</div>
);
}
export default App;
Upvotes: 1
Views: 89
Reputation: 1789
Several changes have been made in the sandbox link
record
as asked in the questionnumber
but not text
since it may need to NaN if user enter string in the input.map
for rendering currentRecord
Upvotes: 1
Reputation:
It looks like your map
should look like this:
{currentRecord.map(item => (
<tr>
<td>1.</td>
<td>{item.currentBook}</td>
<td>{item.units}</td>
<td>{item.price}</td>
</tr>
))
}
Upvotes: 1