Reputation: 25
i made a react class component but it wont increase in value when i try to click button element. any way i can made it to work?
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
function App() {
return (
<div>
<MyButton/>
</div>
);
}
class MyButton extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
incrementCounter() {
this.setState(state => ({
count: state.count + 1
}));
}
render() {
return (
<div>
<p>Counter: {this.state.count}</p>
<button onClick={this.incrementCounter}>
Increment
</button>
</div>
);
}
}
i expect for the button the increase in number accordingly
Upvotes: 1
Views: 83
Reputation: 19070
The problem is that the button click event handler is not correctly bound to the incrementCounter method
You can do:
class MyButton extends React.Component {
constructor(props) {
super(props)
this.state = { count: 0 }
this.incrementCounter = this.incrementCounter.bind(this) // <-- Binding `incrementCounter`
}
incrementCounter() {
this.setState((state) => ({
count: state.count + 1,
}))
}
render() {
return (
<div>
<p>Counter: {this.state.count}</p>
<button onClick={this.incrementCounter}>Increment</button>
</div>
)
}
}
And here is a more clean and functional version:
const MyButton = () => {
const [count, setCount] = useState(0)
const incrementCounter = () => setCount(count + 1)
return (
<div>
<p>Counter: {count}</p>
<button onClick={incrementCounter}>Increment</button>
</div>
)
}
Upvotes: 1