Arash Howaida
Arash Howaida

Reputation: 2617

react - calculate total from state data

I'm new to this library and just trying to complete some proof of concept functions. I have a state with hard coded data that looks like this:

state = { 
    counters: [
        {id: 1, value: 4},
        {id: 2, value: 0},
        {id: 3, value: 1},
        {id: 4, value: 0},
     ],
}

I want to create a function to calculate the total of all values in the state, which would be 5 (4+1). I tried this:

getTotal = () => {
    const counters = [...this.state.counters];
    let total = 0;
    counters.forEach(function(c) {
        total += c.value;
    });
    return total;
}

and added this to my render call:

render() {
    return (
        <React.Fragment>
            <NavBar totalCounters= {this.getTotal}/>
         </React.Fragment>
    );
}

However, in the view, the area is empty. The configuration seems right; if I remove the curly braces content and just put simple text "insert total here", it displays. This leads me to believe my method of calling the function is at fault.

NavBar component is also very simple:

const NavBar = ({totalCounters}) => {
    return ( 
        <nav className="navbar navbar-light bg-light">
            <a className="navbar-brand" href="#">
                Total 
                <span className="badge badge-pill badge-secondary">
                    {totalCounters}
                </span>
            </a>
        </nav>
     );
}
     
export default NavBar;

Question

How can I compute the total of the state values and then display the value in my simple rendered view?

Upvotes: 2

Views: 551

Answers (1)

Pavel Alekseev
Pavel Alekseev

Reputation: 1222

You pass the link to the function and don't invoke it in the children component. So you should change render function:

render() {
  return (
    <React.Fragment>
      <NavBar totalCounters={this.getTotal()} />
    </React.Fragment>
  );
}

Upvotes: 1

Related Questions