In my react app i have some input box for user to put value in and when they press the tambah button the value will be displayed in a table. I am trying to make a total row on the bottom of the table to count the sum of the value from jumlah and make the value displayed get updated every time new data get inputted.
Below are my code
import React, { Component } from 'react';
import './Bootstrap/css/bootstrap.min.css';
class App extends Component {
constructor(){
super();
this.state = {
mahasiswa : [],
tgl : null,
nama : null,
nilai : null
}
}
setValueState(event){
this.setState({
[event.target.name] : event.target.value
})
}
addData(){
var data_tmp = this.state.mahasiswa;
data_tmp.push({nim : this.state.tgl, nama : this.state.nama, nilai : this.state.nilai});
this.setState({
mahasiswa : data_tmp
})
}
render() {
return (
<div className="container">
<h2><b>Daftar Pengeluaran</b></h2>
<div className="form-container">
<div className="form-group">
<label>Waktu:</label>
<input type="text" name="tgl" value={this.state.tgl} onChange={this.setValueState.bind(this)} className="form-control" />
</div>
<div className="form-group">
<label>Deskripsi:</label>
<input type="text" name="nama" value={this.state.nama} onChange={this.setValueState.bind(this)} className="form-control" />
</div>
<div className="form-group">
<label>Jumlah:</label>
<input type="number" name="nilai" value={this.state.nilai} onChange={this.setValueState.bind(this)} className="form-control" />
</div>
<br />
<button onClick={this.addData.bind(this)} type="button" className="btn btn-primary">Tambah</button>
</div>
<br />
<table className="table">
<thead>
<tr><th>No.</th><th>Waktu</th><th>Deskripsi</th><th>Jumlah</th></tr>
</thead>
<tbody>
{this.state.mahasiswa.map((mhs, index)=>(
<tr key={index}>
<td>{index+1}</td><td>{mhs.tgl}</td>
<td>{mhs.nama}</td><td>{mhs.nilai}</td>
</tr>
))}
</tbody>
<tr>Total :</tr>
</table>
</div>
);
}
};
export default App;