Function Result Displayed in Multiple Lines

Asked

Viewed 56 times

0

I need to display the result of the sum of my items in one line only.

I made a function to add the values of a list of objects, the result of the sum is given right but it needs to appear in only one row of my table, now it is appearing in several lines.

How can I fix this?

Thank you!

Follows the code:

<Table striped bordered hover variant="dark">
  <thead>
      <tr>
      <th>Resultado</th>
      </tr>
  </thead>
  <tbody>
      {                           
        this.state.transacoes.map((item, indice)  => {
          var total = this.state.transacoes.reduce(getTotal, 0);
          
          function getTotal(total, item) {
            return total + (item.valor);
          }

          return (                                
            <tr key={indice}>
              <td> {total}</td>
            </tr>                                
            )
        })                         
      }
  </tbody>
</Table>

Code Result:

Resultado do Código

  • 2

    You’re making the map inside the render (or return of a functional component). Why not make a .forEach(), calculate and then create a line with that result?

  • 1

    @Rafaeltavares is a good one, but I think he could use direct 'reduce' without needing 'map', inside an 'IIFE''

1 answer

2


Following the comment of Rafael Tavares, you can make a function that performs a loop forEach in his state.transacoes and with each loop iteration, we will increment the value of a variable called total.

The way you did, you’ll be shown a <td> the amount of item you have in your transacoes, that is, if you have 3 transactions, 3 td, if you have 5, 5 td, and so on...

I point out this alternative I made. What you can do is take this map, and use the reduce directly within a IIFE.

Would that be the code:

<Table striped bordered hover variant="dark">
  <thead>
      <tr>
      <th>Resultado</th>
      </tr>
  </thead>
  <tbody>
      { 
        (() => {
          var total = this.state.transacoes.reduce(getTotal, 0);

          function getTotal(total, item) {
            return total + (item.valor);
          }

          // agora vai retornar somente uma linha no table com o resultado total
          return (
              <tr key={Math.random()}>
              <td> {total}</td>
              </tr>
            )
        })()
      }
  </tbody>
</Table> 

Test this script and see if this is the expected behavior. I hope I helped and you understood the code.

  • I was trying to do it but I wasn’t getting it. Thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.