I don’t understand why this is happening – I have an app that increments and decrements a counter when the buttons are pressed to display an increasing list of easter egg brands from a collection. When the counter reaches the max number of eggs in the collection I want a popup to appear saying “Limit has been reached”. The popup appears, but when I click okay, the same popup shows up again!
Is the React component being called twice somewhere?
If anyone has any ideas, this would be much appreciated.
App.js
JavaScript
x
17
17
1
import logo from './logo.svg';
2
import Counter from './Counter';
3
import EggList from './EggList';
4
import './App.css';
5
6
function App() {
7
8
return (
9
<div className="App">
10
<Counter></Counter>
11
</div>
12
);
13
}
14
15
export default App;
16
17
Counter.js
JavaScript
1
47
47
1
import React from 'react';
2
import EggList from './EggList';
3
4
class Counter extends React.Component {
5
6
constructor(props) {
7
super(props)
8
this.state = {
9
counter: 0
10
}
11
12
this.increment = this.increment.bind(this)
13
this.decrement = this.decrement.bind(this)
14
15
}
16
17
increment(){
18
this.setState({ counter: this.state.counter + 1 })
19
};
20
21
decrement(){
22
this.setState({ counter: this.state.counter - 1 })
23
};
24
25
render() {
26
const { counter } = this.state;
27
var eggsArray = [
28
'Lindt',
29
'Creme Egg',
30
'Oreo',
31
'Cadburys',
32
'Mars',
33
'Aero'
34
];
35
return (
36
<div>
37
<h1 id="counter">{counter}</h1>
38
<button type="button" id="decrement" onClick={this.decrement}>Decrement</button>
39
<button type="button" id="increment" onClick={this.increment}>Increment</button>
40
<EggList eggs={eggsArray} counter={counter}></EggList>
41
</div>
42
)
43
}
44
}
45
46
export default Counter;
47
Egglist.js
JavaScript
1
42
42
1
import React from 'react';
2
3
class EggList extends React.Component {
4
render(){
5
var eggs = [];
6
var upperlimit = false;
7
if(this.props.counter < 0){
8
window.alert("Warning: Counter cannot be less than zero");
9
10
}
11
for(var i = 0; i < this.props.counter; i++){
12
console.log("Counter: " + this.props.counter);
13
console.log("Total eggs: " + this.props.eggs.length);
14
if(this.props.counter > this.props.eggs.length){
15
upperlimit = true;
16
break;
17
}
18
eggs.push(<li key={i.toString()}>{this.props.eggs[i]}</li>);
19
}
20
if(upperlimit === true){
21
console.log('upperlimit');
22
window.alert("Warning: Counter exceeds number of eggs");
23
24
}
25
26
27
28
return (
29
30
31
<ul className="egg-list">
32
{eggs}
33
</ul>
34
)
35
}
36
}
37
38
export default EggList;
39
40
41
42
Thanks,
Robert
London, UK
Advertisement
Answer
Does your index.js have the tag strict mode? If that’s the case, remove it and try again.
JavaScript
1
7
1
ReactDOM.render(
2
<React.StrictMode>
3
<App />
4
</React.StrictMode>,
5
document.getElementById('root')
6
);
7
Try with this:
JavaScript
1
5
1
ReactDOM.render(
2
<App />,
3
document.getElementById('root')
4
);
5