I am trying to share a counter variable among a list of child components. The way I am doing this is by simply maintaining the counter on parent and passing callbacks to the children. Unfortunately weird behaviour is happening where the counter is incrementing 2 times. Any help is appreciated.
import React from "react";
class BenefitRow extends React.Component {
render() {
this.props.incrementer();
console.log(this.props.count());
return (
<div>HEllo</div>
);
}
}
class BenefitSection extends React.Component {
benefitCounter = 0;
incrementer = () => {
console.log("Incrementing!" + this.benefitCounter);
++this.benefitCounter;
};
getBenefitCounter = () => {
return this.benefitCounter;
};
render() {
return (
<div>
<BenefitRow
count={this.getBenefitCounter}
incrementer={this.incrementer}
></BenefitRow>
<BenefitRow
count={this.getBenefitCounter}
incrementer={this.incrementer}
></BenefitRow>
<BenefitRow
count={this.getBenefitCounter}
incrementer={this.incrementer}
></BenefitRow>
</div>
);
}
}
export default BenefitSection
Take a look at console output. There is a interval of two between the count values.