React JS, total score of points
I am new to React js. Right now I am coding an application where user can update points for each team member in a team. Increment and decrement is working very well, I got alot of help here. Right now I am trying to show the total of the points per team. Like the example below, I want the total to update when the points are changed. So if Martin gets a point, total should change to 6. And when Matthew makes a mistake, he loses a point. So then the total should decrease back to 5. But I cant figure out how to do this. Can someone help me ?
Example:
John 0
Matthew 3
Martin 0
Chris 2
Anna 0
Total: 5
My Code:
Counter Component
import React, { Component } from "react";
import ReactDOM from "react-dom";
export default class Counter extends Component {
render() {
const { onIncrement, onDecrement } = this.props;
return (
<div>
<span>{this.formatCount()}</span>
<button onClick={() => onIncrement(this.props.counter)}>
Add
</button>
<button
onClick={() => onDecrement(this.props.counter)}
disabled={this.props.counter.value === 0 ? "disabled" : ""}
>
Delete
</button>
</div>
);
}
formatCount() {
const { value } = this.props.counter;
return value;
}
}
if (document.getElementById("counter")) {
ReactDOM.render(<Counter />, document.getElementById("counter"));
}
Counters component
import React, { Component } from "react";
import ReactDOM from "react-dom";
import Counter from "./counter";
class Counters extends Component {
constructor() {
super();
this.state = {
counters: [
{ id: 1, value: 0 },
{ id: 2, value: 0 },
{ id: 3, value: 0 },
{ id: 4, value: 0 },
{ id: 5, value: 0 }
]
};
}
handleIncrement(counter) {
const counters = [...this.state.counters];
const index = counters.indexOf(counter);
counters[index] = { ...counter };
counters[index].value++;
this.setState({ counters });
}
handleDecrement(counter) {
const counters = [...this.state.counters];
const index = counters.indexOf(counter);
counters[index] = { ...counter };
counters[index].value--;
this.setState({ counters });
}
handleReset() {
const counters = this.state.counters.map(c => {
c.value = 0;
return c;
});
this.setState({ counters });
}
render() {
return (
<div>
<button onClick={this.handleReset.bind(this)}>Reset</button>
{this.state.counters.map(counter => (
<Counter
key={counter.id}
onIncrement={this.handleIncrement.bind(this)}
onDecrement={this.handleDecrement.bind(this)}
counter={counter}
/>
))}
</div>
);
}
}
export default Counters;
if (document.getElementById("counters")) {
ReactDOM.render(<Counters />, document.getElementById("counters"));
}
javascript reactjs laravel
add a comment |
I am new to React js. Right now I am coding an application where user can update points for each team member in a team. Increment and decrement is working very well, I got alot of help here. Right now I am trying to show the total of the points per team. Like the example below, I want the total to update when the points are changed. So if Martin gets a point, total should change to 6. And when Matthew makes a mistake, he loses a point. So then the total should decrease back to 5. But I cant figure out how to do this. Can someone help me ?
Example:
John 0
Matthew 3
Martin 0
Chris 2
Anna 0
Total: 5
My Code:
Counter Component
import React, { Component } from "react";
import ReactDOM from "react-dom";
export default class Counter extends Component {
render() {
const { onIncrement, onDecrement } = this.props;
return (
<div>
<span>{this.formatCount()}</span>
<button onClick={() => onIncrement(this.props.counter)}>
Add
</button>
<button
onClick={() => onDecrement(this.props.counter)}
disabled={this.props.counter.value === 0 ? "disabled" : ""}
>
Delete
</button>
</div>
);
}
formatCount() {
const { value } = this.props.counter;
return value;
}
}
if (document.getElementById("counter")) {
ReactDOM.render(<Counter />, document.getElementById("counter"));
}
Counters component
import React, { Component } from "react";
import ReactDOM from "react-dom";
import Counter from "./counter";
class Counters extends Component {
constructor() {
super();
this.state = {
counters: [
{ id: 1, value: 0 },
{ id: 2, value: 0 },
{ id: 3, value: 0 },
{ id: 4, value: 0 },
{ id: 5, value: 0 }
]
};
}
handleIncrement(counter) {
const counters = [...this.state.counters];
const index = counters.indexOf(counter);
counters[index] = { ...counter };
counters[index].value++;
this.setState({ counters });
}
handleDecrement(counter) {
const counters = [...this.state.counters];
const index = counters.indexOf(counter);
counters[index] = { ...counter };
counters[index].value--;
this.setState({ counters });
}
handleReset() {
const counters = this.state.counters.map(c => {
c.value = 0;
return c;
});
this.setState({ counters });
}
render() {
return (
<div>
<button onClick={this.handleReset.bind(this)}>Reset</button>
{this.state.counters.map(counter => (
<Counter
key={counter.id}
onIncrement={this.handleIncrement.bind(this)}
onDecrement={this.handleDecrement.bind(this)}
counter={counter}
/>
))}
</div>
);
}
}
export default Counters;
if (document.getElementById("counters")) {
ReactDOM.render(<Counters />, document.getElementById("counters"));
}
javascript reactjs laravel
add a comment |
I am new to React js. Right now I am coding an application where user can update points for each team member in a team. Increment and decrement is working very well, I got alot of help here. Right now I am trying to show the total of the points per team. Like the example below, I want the total to update when the points are changed. So if Martin gets a point, total should change to 6. And when Matthew makes a mistake, he loses a point. So then the total should decrease back to 5. But I cant figure out how to do this. Can someone help me ?
Example:
John 0
Matthew 3
Martin 0
Chris 2
Anna 0
Total: 5
My Code:
Counter Component
import React, { Component } from "react";
import ReactDOM from "react-dom";
export default class Counter extends Component {
render() {
const { onIncrement, onDecrement } = this.props;
return (
<div>
<span>{this.formatCount()}</span>
<button onClick={() => onIncrement(this.props.counter)}>
Add
</button>
<button
onClick={() => onDecrement(this.props.counter)}
disabled={this.props.counter.value === 0 ? "disabled" : ""}
>
Delete
</button>
</div>
);
}
formatCount() {
const { value } = this.props.counter;
return value;
}
}
if (document.getElementById("counter")) {
ReactDOM.render(<Counter />, document.getElementById("counter"));
}
Counters component
import React, { Component } from "react";
import ReactDOM from "react-dom";
import Counter from "./counter";
class Counters extends Component {
constructor() {
super();
this.state = {
counters: [
{ id: 1, value: 0 },
{ id: 2, value: 0 },
{ id: 3, value: 0 },
{ id: 4, value: 0 },
{ id: 5, value: 0 }
]
};
}
handleIncrement(counter) {
const counters = [...this.state.counters];
const index = counters.indexOf(counter);
counters[index] = { ...counter };
counters[index].value++;
this.setState({ counters });
}
handleDecrement(counter) {
const counters = [...this.state.counters];
const index = counters.indexOf(counter);
counters[index] = { ...counter };
counters[index].value--;
this.setState({ counters });
}
handleReset() {
const counters = this.state.counters.map(c => {
c.value = 0;
return c;
});
this.setState({ counters });
}
render() {
return (
<div>
<button onClick={this.handleReset.bind(this)}>Reset</button>
{this.state.counters.map(counter => (
<Counter
key={counter.id}
onIncrement={this.handleIncrement.bind(this)}
onDecrement={this.handleDecrement.bind(this)}
counter={counter}
/>
))}
</div>
);
}
}
export default Counters;
if (document.getElementById("counters")) {
ReactDOM.render(<Counters />, document.getElementById("counters"));
}
javascript reactjs laravel
I am new to React js. Right now I am coding an application where user can update points for each team member in a team. Increment and decrement is working very well, I got alot of help here. Right now I am trying to show the total of the points per team. Like the example below, I want the total to update when the points are changed. So if Martin gets a point, total should change to 6. And when Matthew makes a mistake, he loses a point. So then the total should decrease back to 5. But I cant figure out how to do this. Can someone help me ?
Example:
John 0
Matthew 3
Martin 0
Chris 2
Anna 0
Total: 5
My Code:
Counter Component
import React, { Component } from "react";
import ReactDOM from "react-dom";
export default class Counter extends Component {
render() {
const { onIncrement, onDecrement } = this.props;
return (
<div>
<span>{this.formatCount()}</span>
<button onClick={() => onIncrement(this.props.counter)}>
Add
</button>
<button
onClick={() => onDecrement(this.props.counter)}
disabled={this.props.counter.value === 0 ? "disabled" : ""}
>
Delete
</button>
</div>
);
}
formatCount() {
const { value } = this.props.counter;
return value;
}
}
if (document.getElementById("counter")) {
ReactDOM.render(<Counter />, document.getElementById("counter"));
}
Counters component
import React, { Component } from "react";
import ReactDOM from "react-dom";
import Counter from "./counter";
class Counters extends Component {
constructor() {
super();
this.state = {
counters: [
{ id: 1, value: 0 },
{ id: 2, value: 0 },
{ id: 3, value: 0 },
{ id: 4, value: 0 },
{ id: 5, value: 0 }
]
};
}
handleIncrement(counter) {
const counters = [...this.state.counters];
const index = counters.indexOf(counter);
counters[index] = { ...counter };
counters[index].value++;
this.setState({ counters });
}
handleDecrement(counter) {
const counters = [...this.state.counters];
const index = counters.indexOf(counter);
counters[index] = { ...counter };
counters[index].value--;
this.setState({ counters });
}
handleReset() {
const counters = this.state.counters.map(c => {
c.value = 0;
return c;
});
this.setState({ counters });
}
render() {
return (
<div>
<button onClick={this.handleReset.bind(this)}>Reset</button>
{this.state.counters.map(counter => (
<Counter
key={counter.id}
onIncrement={this.handleIncrement.bind(this)}
onDecrement={this.handleDecrement.bind(this)}
counter={counter}
/>
))}
</div>
);
}
}
export default Counters;
if (document.getElementById("counters")) {
ReactDOM.render(<Counters />, document.getElementById("counters"));
}
javascript reactjs laravel
javascript reactjs laravel
asked Nov 25 '18 at 6:06
14mble14mble
195
195
add a comment |
add a comment |
2 Answers
2
active
oldest
votes
You can add a line for the totals by adding another property to your state along with counters called total. This total value will need to be changed on calls to increment, decrement and reset.
Below is a demonstration of how this is accomplished:
class Counter extends React.Component {
render() {
const { onIncrement, onDecrement } = this.props;
return (
<div>
<span>{this.formatCount()}</span>
<button onClick={() => onIncrement(this.props.counter)}>
Add
</button>
<button
onClick={() => onDecrement(this.props.counter)}
disabled={this.props.counter.value === 0 ? "disabled" : ""}
>
Delete
</button>
</div>
);
}
formatCount() {
const { value } = this.props.counter;
return value;
}
}
class Counters extends React.Component {
constructor() {
super();
this.state = {
counters: [
{ id: 1, value: 0 },
{ id: 2, value: 0 },
{ id: 3, value: 0 },
{ id: 4, value: 0 },
{ id: 5, value: 0 }
],
total: 0
};
}
handleIncrement(counter) {
const total = this.state.total + 1;
const counters = [...this.state.counters];
const index = counters.indexOf(counter);
counters[index] = { ...counter };
counters[index].value++;
this.setState({ counters: counters, total: total });
}
handleDecrement(counter) {
const total = this.state.total - 1;
const counters = [...this.state.counters];
const index = counters.indexOf(counter);
counters[index] = { ...counter };
counters[index].value--;
this.setState({ counters: counters, total: total });
}
handleReset() {
const total = 0;
const counters = this.state.counters.map(c => {
c.value = 0;
return c;
});
this.setState({ counters: counters, total: total });
}
render() {
return (
<div>
<button onClick={this.handleReset.bind(this)}>Reset</button>
{this.state.counters.map(counter => (
<Counter
key={counter.id}
onIncrement={this.handleIncrement.bind(this)}
onDecrement={this.handleDecrement.bind(this)}
counter={counter}
/>
))}
<div>Total: {this.state.total}</div>
</div>
);
}
}
ReactDOM.render(
<Counters/>,
document.getElementById("react")
);<div id="react"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>Alternatively you can skip storing the total value in state and dynamically find the total value based on the counters values like so:
<div>Total: {this.state.counters.map((counter) => { return counter.value; }).reduce((a, b) => a + b, 0);}</div>
add a comment |
There are two options:
Calculate total in render:
const total = this.state.counters.reduce((sum, counter) => sum + counter.value, 0)(see Array.prototype.reduce())Increment/decrement total with counters:
this.setState(oldState => ({total: oldState.total + 1}))
As a good habbit you should not use this.state to get a value for setState because there can be multiple increment/decrement events. Use this syntax instead: setState(oldState => {/* some code */; return newState}).
Also it is better to pass {...counter} instead of counter={counter} and use id to find counter inside handleIncrement/handleDecrement. It is easier to track changes to props and avoid unnecessary renders this way. And there will be no problems with multiple simultaneous events on the same counter.
Thanks for the tips!
– 14mble
Nov 26 '18 at 0:52
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53465076%2freact-js-total-score-of-points%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
You can add a line for the totals by adding another property to your state along with counters called total. This total value will need to be changed on calls to increment, decrement and reset.
Below is a demonstration of how this is accomplished:
class Counter extends React.Component {
render() {
const { onIncrement, onDecrement } = this.props;
return (
<div>
<span>{this.formatCount()}</span>
<button onClick={() => onIncrement(this.props.counter)}>
Add
</button>
<button
onClick={() => onDecrement(this.props.counter)}
disabled={this.props.counter.value === 0 ? "disabled" : ""}
>
Delete
</button>
</div>
);
}
formatCount() {
const { value } = this.props.counter;
return value;
}
}
class Counters extends React.Component {
constructor() {
super();
this.state = {
counters: [
{ id: 1, value: 0 },
{ id: 2, value: 0 },
{ id: 3, value: 0 },
{ id: 4, value: 0 },
{ id: 5, value: 0 }
],
total: 0
};
}
handleIncrement(counter) {
const total = this.state.total + 1;
const counters = [...this.state.counters];
const index = counters.indexOf(counter);
counters[index] = { ...counter };
counters[index].value++;
this.setState({ counters: counters, total: total });
}
handleDecrement(counter) {
const total = this.state.total - 1;
const counters = [...this.state.counters];
const index = counters.indexOf(counter);
counters[index] = { ...counter };
counters[index].value--;
this.setState({ counters: counters, total: total });
}
handleReset() {
const total = 0;
const counters = this.state.counters.map(c => {
c.value = 0;
return c;
});
this.setState({ counters: counters, total: total });
}
render() {
return (
<div>
<button onClick={this.handleReset.bind(this)}>Reset</button>
{this.state.counters.map(counter => (
<Counter
key={counter.id}
onIncrement={this.handleIncrement.bind(this)}
onDecrement={this.handleDecrement.bind(this)}
counter={counter}
/>
))}
<div>Total: {this.state.total}</div>
</div>
);
}
}
ReactDOM.render(
<Counters/>,
document.getElementById("react")
);<div id="react"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>Alternatively you can skip storing the total value in state and dynamically find the total value based on the counters values like so:
<div>Total: {this.state.counters.map((counter) => { return counter.value; }).reduce((a, b) => a + b, 0);}</div>
add a comment |
You can add a line for the totals by adding another property to your state along with counters called total. This total value will need to be changed on calls to increment, decrement and reset.
Below is a demonstration of how this is accomplished:
class Counter extends React.Component {
render() {
const { onIncrement, onDecrement } = this.props;
return (
<div>
<span>{this.formatCount()}</span>
<button onClick={() => onIncrement(this.props.counter)}>
Add
</button>
<button
onClick={() => onDecrement(this.props.counter)}
disabled={this.props.counter.value === 0 ? "disabled" : ""}
>
Delete
</button>
</div>
);
}
formatCount() {
const { value } = this.props.counter;
return value;
}
}
class Counters extends React.Component {
constructor() {
super();
this.state = {
counters: [
{ id: 1, value: 0 },
{ id: 2, value: 0 },
{ id: 3, value: 0 },
{ id: 4, value: 0 },
{ id: 5, value: 0 }
],
total: 0
};
}
handleIncrement(counter) {
const total = this.state.total + 1;
const counters = [...this.state.counters];
const index = counters.indexOf(counter);
counters[index] = { ...counter };
counters[index].value++;
this.setState({ counters: counters, total: total });
}
handleDecrement(counter) {
const total = this.state.total - 1;
const counters = [...this.state.counters];
const index = counters.indexOf(counter);
counters[index] = { ...counter };
counters[index].value--;
this.setState({ counters: counters, total: total });
}
handleReset() {
const total = 0;
const counters = this.state.counters.map(c => {
c.value = 0;
return c;
});
this.setState({ counters: counters, total: total });
}
render() {
return (
<div>
<button onClick={this.handleReset.bind(this)}>Reset</button>
{this.state.counters.map(counter => (
<Counter
key={counter.id}
onIncrement={this.handleIncrement.bind(this)}
onDecrement={this.handleDecrement.bind(this)}
counter={counter}
/>
))}
<div>Total: {this.state.total}</div>
</div>
);
}
}
ReactDOM.render(
<Counters/>,
document.getElementById("react")
);<div id="react"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>Alternatively you can skip storing the total value in state and dynamically find the total value based on the counters values like so:
<div>Total: {this.state.counters.map((counter) => { return counter.value; }).reduce((a, b) => a + b, 0);}</div>
add a comment |
You can add a line for the totals by adding another property to your state along with counters called total. This total value will need to be changed on calls to increment, decrement and reset.
Below is a demonstration of how this is accomplished:
class Counter extends React.Component {
render() {
const { onIncrement, onDecrement } = this.props;
return (
<div>
<span>{this.formatCount()}</span>
<button onClick={() => onIncrement(this.props.counter)}>
Add
</button>
<button
onClick={() => onDecrement(this.props.counter)}
disabled={this.props.counter.value === 0 ? "disabled" : ""}
>
Delete
</button>
</div>
);
}
formatCount() {
const { value } = this.props.counter;
return value;
}
}
class Counters extends React.Component {
constructor() {
super();
this.state = {
counters: [
{ id: 1, value: 0 },
{ id: 2, value: 0 },
{ id: 3, value: 0 },
{ id: 4, value: 0 },
{ id: 5, value: 0 }
],
total: 0
};
}
handleIncrement(counter) {
const total = this.state.total + 1;
const counters = [...this.state.counters];
const index = counters.indexOf(counter);
counters[index] = { ...counter };
counters[index].value++;
this.setState({ counters: counters, total: total });
}
handleDecrement(counter) {
const total = this.state.total - 1;
const counters = [...this.state.counters];
const index = counters.indexOf(counter);
counters[index] = { ...counter };
counters[index].value--;
this.setState({ counters: counters, total: total });
}
handleReset() {
const total = 0;
const counters = this.state.counters.map(c => {
c.value = 0;
return c;
});
this.setState({ counters: counters, total: total });
}
render() {
return (
<div>
<button onClick={this.handleReset.bind(this)}>Reset</button>
{this.state.counters.map(counter => (
<Counter
key={counter.id}
onIncrement={this.handleIncrement.bind(this)}
onDecrement={this.handleDecrement.bind(this)}
counter={counter}
/>
))}
<div>Total: {this.state.total}</div>
</div>
);
}
}
ReactDOM.render(
<Counters/>,
document.getElementById("react")
);<div id="react"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>Alternatively you can skip storing the total value in state and dynamically find the total value based on the counters values like so:
<div>Total: {this.state.counters.map((counter) => { return counter.value; }).reduce((a, b) => a + b, 0);}</div>
You can add a line for the totals by adding another property to your state along with counters called total. This total value will need to be changed on calls to increment, decrement and reset.
Below is a demonstration of how this is accomplished:
class Counter extends React.Component {
render() {
const { onIncrement, onDecrement } = this.props;
return (
<div>
<span>{this.formatCount()}</span>
<button onClick={() => onIncrement(this.props.counter)}>
Add
</button>
<button
onClick={() => onDecrement(this.props.counter)}
disabled={this.props.counter.value === 0 ? "disabled" : ""}
>
Delete
</button>
</div>
);
}
formatCount() {
const { value } = this.props.counter;
return value;
}
}
class Counters extends React.Component {
constructor() {
super();
this.state = {
counters: [
{ id: 1, value: 0 },
{ id: 2, value: 0 },
{ id: 3, value: 0 },
{ id: 4, value: 0 },
{ id: 5, value: 0 }
],
total: 0
};
}
handleIncrement(counter) {
const total = this.state.total + 1;
const counters = [...this.state.counters];
const index = counters.indexOf(counter);
counters[index] = { ...counter };
counters[index].value++;
this.setState({ counters: counters, total: total });
}
handleDecrement(counter) {
const total = this.state.total - 1;
const counters = [...this.state.counters];
const index = counters.indexOf(counter);
counters[index] = { ...counter };
counters[index].value--;
this.setState({ counters: counters, total: total });
}
handleReset() {
const total = 0;
const counters = this.state.counters.map(c => {
c.value = 0;
return c;
});
this.setState({ counters: counters, total: total });
}
render() {
return (
<div>
<button onClick={this.handleReset.bind(this)}>Reset</button>
{this.state.counters.map(counter => (
<Counter
key={counter.id}
onIncrement={this.handleIncrement.bind(this)}
onDecrement={this.handleDecrement.bind(this)}
counter={counter}
/>
))}
<div>Total: {this.state.total}</div>
</div>
);
}
}
ReactDOM.render(
<Counters/>,
document.getElementById("react")
);<div id="react"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>Alternatively you can skip storing the total value in state and dynamically find the total value based on the counters values like so:
<div>Total: {this.state.counters.map((counter) => { return counter.value; }).reduce((a, b) => a + b, 0);}</div>
class Counter extends React.Component {
render() {
const { onIncrement, onDecrement } = this.props;
return (
<div>
<span>{this.formatCount()}</span>
<button onClick={() => onIncrement(this.props.counter)}>
Add
</button>
<button
onClick={() => onDecrement(this.props.counter)}
disabled={this.props.counter.value === 0 ? "disabled" : ""}
>
Delete
</button>
</div>
);
}
formatCount() {
const { value } = this.props.counter;
return value;
}
}
class Counters extends React.Component {
constructor() {
super();
this.state = {
counters: [
{ id: 1, value: 0 },
{ id: 2, value: 0 },
{ id: 3, value: 0 },
{ id: 4, value: 0 },
{ id: 5, value: 0 }
],
total: 0
};
}
handleIncrement(counter) {
const total = this.state.total + 1;
const counters = [...this.state.counters];
const index = counters.indexOf(counter);
counters[index] = { ...counter };
counters[index].value++;
this.setState({ counters: counters, total: total });
}
handleDecrement(counter) {
const total = this.state.total - 1;
const counters = [...this.state.counters];
const index = counters.indexOf(counter);
counters[index] = { ...counter };
counters[index].value--;
this.setState({ counters: counters, total: total });
}
handleReset() {
const total = 0;
const counters = this.state.counters.map(c => {
c.value = 0;
return c;
});
this.setState({ counters: counters, total: total });
}
render() {
return (
<div>
<button onClick={this.handleReset.bind(this)}>Reset</button>
{this.state.counters.map(counter => (
<Counter
key={counter.id}
onIncrement={this.handleIncrement.bind(this)}
onDecrement={this.handleDecrement.bind(this)}
counter={counter}
/>
))}
<div>Total: {this.state.total}</div>
</div>
);
}
}
ReactDOM.render(
<Counters/>,
document.getElementById("react")
);<div id="react"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>class Counter extends React.Component {
render() {
const { onIncrement, onDecrement } = this.props;
return (
<div>
<span>{this.formatCount()}</span>
<button onClick={() => onIncrement(this.props.counter)}>
Add
</button>
<button
onClick={() => onDecrement(this.props.counter)}
disabled={this.props.counter.value === 0 ? "disabled" : ""}
>
Delete
</button>
</div>
);
}
formatCount() {
const { value } = this.props.counter;
return value;
}
}
class Counters extends React.Component {
constructor() {
super();
this.state = {
counters: [
{ id: 1, value: 0 },
{ id: 2, value: 0 },
{ id: 3, value: 0 },
{ id: 4, value: 0 },
{ id: 5, value: 0 }
],
total: 0
};
}
handleIncrement(counter) {
const total = this.state.total + 1;
const counters = [...this.state.counters];
const index = counters.indexOf(counter);
counters[index] = { ...counter };
counters[index].value++;
this.setState({ counters: counters, total: total });
}
handleDecrement(counter) {
const total = this.state.total - 1;
const counters = [...this.state.counters];
const index = counters.indexOf(counter);
counters[index] = { ...counter };
counters[index].value--;
this.setState({ counters: counters, total: total });
}
handleReset() {
const total = 0;
const counters = this.state.counters.map(c => {
c.value = 0;
return c;
});
this.setState({ counters: counters, total: total });
}
render() {
return (
<div>
<button onClick={this.handleReset.bind(this)}>Reset</button>
{this.state.counters.map(counter => (
<Counter
key={counter.id}
onIncrement={this.handleIncrement.bind(this)}
onDecrement={this.handleDecrement.bind(this)}
counter={counter}
/>
))}
<div>Total: {this.state.total}</div>
</div>
);
}
}
ReactDOM.render(
<Counters/>,
document.getElementById("react")
);<div id="react"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>answered Nov 25 '18 at 6:49
Shawn AndrewsShawn Andrews
965617
965617
add a comment |
add a comment |
There are two options:
Calculate total in render:
const total = this.state.counters.reduce((sum, counter) => sum + counter.value, 0)(see Array.prototype.reduce())Increment/decrement total with counters:
this.setState(oldState => ({total: oldState.total + 1}))
As a good habbit you should not use this.state to get a value for setState because there can be multiple increment/decrement events. Use this syntax instead: setState(oldState => {/* some code */; return newState}).
Also it is better to pass {...counter} instead of counter={counter} and use id to find counter inside handleIncrement/handleDecrement. It is easier to track changes to props and avoid unnecessary renders this way. And there will be no problems with multiple simultaneous events on the same counter.
Thanks for the tips!
– 14mble
Nov 26 '18 at 0:52
add a comment |
There are two options:
Calculate total in render:
const total = this.state.counters.reduce((sum, counter) => sum + counter.value, 0)(see Array.prototype.reduce())Increment/decrement total with counters:
this.setState(oldState => ({total: oldState.total + 1}))
As a good habbit you should not use this.state to get a value for setState because there can be multiple increment/decrement events. Use this syntax instead: setState(oldState => {/* some code */; return newState}).
Also it is better to pass {...counter} instead of counter={counter} and use id to find counter inside handleIncrement/handleDecrement. It is easier to track changes to props and avoid unnecessary renders this way. And there will be no problems with multiple simultaneous events on the same counter.
Thanks for the tips!
– 14mble
Nov 26 '18 at 0:52
add a comment |
There are two options:
Calculate total in render:
const total = this.state.counters.reduce((sum, counter) => sum + counter.value, 0)(see Array.prototype.reduce())Increment/decrement total with counters:
this.setState(oldState => ({total: oldState.total + 1}))
As a good habbit you should not use this.state to get a value for setState because there can be multiple increment/decrement events. Use this syntax instead: setState(oldState => {/* some code */; return newState}).
Also it is better to pass {...counter} instead of counter={counter} and use id to find counter inside handleIncrement/handleDecrement. It is easier to track changes to props and avoid unnecessary renders this way. And there will be no problems with multiple simultaneous events on the same counter.
There are two options:
Calculate total in render:
const total = this.state.counters.reduce((sum, counter) => sum + counter.value, 0)(see Array.prototype.reduce())Increment/decrement total with counters:
this.setState(oldState => ({total: oldState.total + 1}))
As a good habbit you should not use this.state to get a value for setState because there can be multiple increment/decrement events. Use this syntax instead: setState(oldState => {/* some code */; return newState}).
Also it is better to pass {...counter} instead of counter={counter} and use id to find counter inside handleIncrement/handleDecrement. It is easier to track changes to props and avoid unnecessary renders this way. And there will be no problems with multiple simultaneous events on the same counter.
answered Nov 25 '18 at 6:49
UjinT34UjinT34
78410
78410
Thanks for the tips!
– 14mble
Nov 26 '18 at 0:52
add a comment |
Thanks for the tips!
– 14mble
Nov 26 '18 at 0:52
Thanks for the tips!
– 14mble
Nov 26 '18 at 0:52
Thanks for the tips!
– 14mble
Nov 26 '18 at 0:52
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53465076%2freact-js-total-score-of-points%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown