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
import logo from './logo.svg'; import Counter from './Counter'; import EggList from './EggList'; import './App.css'; function App() { return ( <div className="App"> <Counter></Counter> </div> ); } export default App;
Counter.js
import React from 'react'; import EggList from './EggList'; class Counter extends React.Component { constructor(props) { super(props) this.state = { counter: 0 } this.increment = this.increment.bind(this) this.decrement = this.decrement.bind(this) } increment(){ this.setState({ counter: this.state.counter + 1 }) }; decrement(){ this.setState({ counter: this.state.counter - 1 }) }; render() { const { counter } = this.state; var eggsArray = [ 'Lindt', 'Creme Egg', 'Oreo', 'Cadburys', 'Mars', 'Aero' ]; return ( <div> <h1 id="counter">{counter}</h1> <button type="button" id="decrement" onClick={this.decrement}>Decrement</button> <button type="button" id="increment" onClick={this.increment}>Increment</button> <EggList eggs={eggsArray} counter={counter}></EggList> </div> ) } } export default Counter;
Egglist.js
import React from 'react'; class EggList extends React.Component { render(){ var eggs = []; var upperlimit = false; if(this.props.counter < 0){ window.alert("Warning: Counter cannot be less than zero"); } for(var i = 0; i < this.props.counter; i++){ console.log("Counter: " + this.props.counter); console.log("Total eggs: " + this.props.eggs.length); if(this.props.counter > this.props.eggs.length){ upperlimit = true; break; } eggs.push(<li key={i.toString()}>{this.props.eggs[i]}</li>); } if(upperlimit === true){ console.log('upperlimit'); window.alert("Warning: Counter exceeds number of eggs"); } return ( <ul className="egg-list"> {eggs} </ul> ) } } export default EggList;
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.
ReactDOM.render( <React.StrictMode> <App /> </React.StrictMode>, document.getElementById('root') );
Try with this:
ReactDOM.render( <App />, document.getElementById('root') );