Home > Blockchain >  How to get sum of column values for each row in React JS?
How to get sum of column values for each row in React JS?

Time:07-12

How can i get sum of column values for each row and push each row's total in rowTotalArray.

Image is Here

The number of rows and input fields are dynamic. When user enters number in input field for each column in row , last column (Total) must show sum of column value for each row.

import React, { useEffect, useState } from 'react';
import { useSelector } from 'react-redux';
import Table from 'react-bootstrap/Table';

function RowWiseSum() {
    const datas = useSelector(state => state.dataList.datas);
   
    const [group, setGroup] = useState([{
        g1: 0,
        g2: 0,
        g3: 0,
    }]);

    const [sum, setSum] = useState(0);
    const [rowTotalArray, setRowTotalArray] = useState([]); 
  
    useEffect(() => {
        let sum = parseFloat(group.g1)   parseFloat(group.g2)   parseFloat(group.g3);
       setSum(sum);
    }, [group])

    return (
        <Table striped bordered size="sm" style={{ fontSize: '12px' }}>
            <thead>
                <tr>
                    <th>Sn</th>
                    <th>Title</th>
                    <th>No. in G1</th>
                    <th>No. in G2</th>
                    <th>No. in G3</th>
                    <th>Total</th>
                </tr>
            </thead>
            <tbody>
                {
                   datas.map((data, i) => 
                    (
                        <tr key={i}>
                            <td>{data.sno}</td>
                            <td>{data.description}</td>
                            <td>
                                <input type='text' name={`g1-${i 1}`} onChange={(e) => setGroup({ ...group, g1: e.target.value })} />
                            </td>
                            <td>
                                <input type='text'  name={`g2-${i 1}`}   onChange={(e) => setGroup({ ...group, g2: e.target.value })} />
                            </td>
                            <td>
                                <input type='text'  name={`g3-${i 1}`} onChange={(e) => setGroup({ ...group, g3: e.target.value })} />
                            </td>
                    
                            <td>
                                <input type='text' readOnly value={sum} name={`sum-${i 1}`} />
                            </td>
                        </tr>
                        
                    ))
                }
            </tbody>
        </Table>
    )
}
export default RowWiseSum

CodePudding user response:

Your group state should be array of each row point, so you can caculate total of each row

const defaultGroup = datas.map((i) => ({
  g1: 0,
  g2: 0,
  g3: 0
}));
const [group, setGroup] = useState(defaultGroup);
const onChange = (type, value, index) => {
  const newGroup = group.map((g, idx) => {
    if (index === idx)
      return {
        ...g,
        [type]: parseInt(value || 0)
      };
    return g;
  });
  setGroup(newGroup);
};

const total = group.reduce((acc, cur) => {
  acc  = cur.g1   cur.g2   cur.g3;
  return acc;
}, 0);
return (
  <div className="App">
    <table striped bordered size="sm" style={{ fontSize: "12px" }}>
      <thead>
        <tr>
          <th>Sn</th>
          <th>Title</th>
          <th>No. in G1</th>
          <th>No. in G2</th>
          <th>No. in G3</th>
          <th>Total</th>
        </tr>
      </thead>
      <tbody>
        {datas.map((data, i) => (
          <tr key={i}>
            <td>{data.sno}</td>
            <td>{data.description}</td>
            <td>
              <input
                type="number"
                name={`g1-${i   1}`}
                defaultValue={group[i].g1}
                onChange={(e) => onChange("g1", e.target.value, i)}
              />
            </td>
            <td>
              <input
                type="number"
                name={`g2-${i   1}`}
                defaultValue={group[i].g2}
                onChange={(e) => onChange("g2", e.target.value, i)}
              />
            </td>
            <td>
              <input
                type="number"
                name={`g3-${i   1}`}
                defaultValue={group[i].g3}
                onChange={(e) => onChange("g3", e.target.value, i)}
              />
            </td>

            <td>
              <input
                type="text"
                readOnly
                name={`sum-${i   1}`}
                value={group[i].g1   group[i].g2   group[i].g3}
              />
            </td>
          </tr>
        ))}
      </tbody>
    </table>
    <div>TOTAL: {total}</div>
  </div>
);

I've created a codesandbox, you can check it. Hope it help!

CodePudding user response:

your group state should be like this const [group, setGroup] = useState({ g1: 0, g2: 0, g3: 0, });

instead of const [group, setGroup] = useState([{g1: 0, g2: 0, g3: 0,}])

  • Related