EDITED
So I have a Counter button component which I am rendering in my App. My App contains the state for the counter but how do I pass it as props to the Counter component? At the moment Counter has its own state but I want it to be using the state in App.
Also I am trying to make a universal counter button in a separate component which will increment/decrement the duplicate Counter buttons. But I have the same issue where I am not sure how to correclty pass the App's state as props into this universal button.
Universal Counter:
class UniversalCounter extends Component {
constructor(props) {
super(props);
const allCounter = [Counter]
this.state = allCounter;
}
incrementCount() {
this.setState(prevState => ({ allCounter: prevState.allCounter + 1 }));
}
decrementCount() {
this.setState(prevState => ({ allCounter: prevState.allCounter - 1 }));
}
render() {
let { allCounter } = this.state;
return (
<div>
<h2>All Counters</h2>
<button onClick={() => this.incrementCount(allCounter)}>increase all</button>
<button onClick={() => this.decrementCount(allCounter)}>decrease all</button>
</div>
);
}
Counter Component:
class Counter extends Component {
constructor(props) {
super(props);
this.state = { counter: 0 };
}
incrementCount() {
this.setState(prevState => ({ counter: prevState.counter+ 1 }));
}
decrementCount() {
this.setState(prevState => ({ counter: prevState.counter- 1 }));
}
render() {
let { counter} = this.state;
return (
<div>
<h2>Count: {counter}</h2>
<button onClick={() => this.incrementCount(counter)}>+</button>
<button onClick={() => this.decrementCount(counter)}>-</button>
</div>
);
}
}
App:
class App extends Component {
constructor(props) {
super(props);
this.state = { counter: 0 };
}
render() {
let { counter } = this.state;
return (
<div className="App">
<Counter/>
<Counter/>
<Counter/>
<UniversalCounter />
</div>
);
}
}
export default App;