THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.
It is a short tutorial on how to get a sum of numbers in React application.
Let’s consider the array of objects as given below.
[{
firstName: "John",
lastName: "Erwin",
email: "john@gmail.com",
salary:5000
},
{
firstName: "Ram",
lastName: "Kumar",
email: "john@gmail.com",
salary:5000
}
]
An array contains objects with different employee properties.
Let’s see an example of how to print an array of objects into an HTML table, and also calculate the sum of object numeric values and display it in React component.
NumberSum
table
thead
, tbody
and tfoot
.map
method and construct a string with all tr
and td
of rows and columns.reduce
method which has accumulator initialized to 0 initially and add currentItem salary into the accumulator and finally return the sum of salaryimport React, { Component } from 'react';
import { render } from 'react-dom';
export default class NumberSum extends Component {
constructor(props) {
super(props);
this.state = {
data: [{
firstName: "John",
lastName: "Erwin",
email: "john@gmail.com",
salary:5000},
{firstName: "Ram",
lastName: "Kumar",
email: "john@gmail.com",
salary:5000
}]}
}
render() {
const tableBody=this.state.data.map((item =>
<tr key={item.firstname}><td >{item.firstName}</td><td >{item.lastName}</td><td >{item.email}</td><td>{item.salary}</td>
</tr>
));
const total=(this.state.data.reduce((total,currentItem) => total = total + currentItem.salary , 0 ));
return (
<table>
<thead><tr><th>first</th>
<th>last</th>
<th>Email</th>
<th>Salary</th>
</tr>
</thead>
<tbody>{tableBody}
</tbody>
<tfoot><tr>
Total:
{total}
</tr>
</tfoot>
</table>)
}
}
Output
This is a short tutorial with examples in react
🧮 Tags
Recent posts
Three dots in react components with example|Spread operator How to update ReactJS's `create-react-app`? Difference between super and super props in React constructor class? How to check the element index of a list or array in the swift example How to calculate the sum of all numbers or object values in Array swift with exampleRelated posts