Increase and Decrease Number onClick in React

Sometimes, when writing real-time React software applications, there are times when you want to increase and decrease a number when a button is clicked.
A good example is increasing the quantity of an item in a cart or counting page visits. This can be done easily in React.
So we are going to create a basic React application. Let’s begin
1. Set Initial State
The first thing we want to do is set our initial state in the React application
class App extends Component {
constructor(props) {
super(props);
this.state = {
clicks:0,
show:true
};
}
}
export default App;
As we can see in the code above, we have set our initial state variable to 0. It is important to note that it must not always be 0, you can start from any number you wish.
If, for instance, you are incrementing cart items, then you can’t have 0 items in a cart in terms of quantity. You want the least quantity to 1, which makes sense.
2. We write Increment, Decrement and Toggle Functions
incrementValue = () => {
this.setState({ clicks: this.state.clicks + 1 });
}
decreaseValue = () => {
this.setState({ clicks: this.state.clicks - 1 });
}
toggleClick = () => {
this.setState({ show: !this.state.show });
}
IncrementValue(): increases the state variable by 1
decrementValue(): decreases the state variable by 1
toggleClick(): flips our state show for opposite every time we click. This will increase and decrease number on click in React
3. Pass the functions to the button
render() {
return (
<div>
<button onClick={this.incrementValue}>Click to increment by </button>
<button onClick={this.decreaseValue}>Click to decrease by </button>
<button onClick={this.toggleClick}>
{ this.state.show ? 'Hide number' : 'Show number' }
</button>
{ this.state.show ? <h2>{ this.state.clicks }</h2> : '' }
</div>
);
If you want to restrict to the state value to 1 instead of 0 as said earlier, you modify the c like so:
decreaseValue = () => {
if(this.state.clicks > 1){
this.setState({ clicks: this.state.clicks - 1 });
}else{
this.setState({ clicks: 1 });
}
}
Here’s the full code
import React, { Component } from 'react';
class App extends Component {
constructor(props) {
super(props);
this.state = {
clicks: 0,
show: true
};
}
incrementValue = () => {
this.setState({ clicks: this.state.clicks + 1 });
}
decreaseValue = () => {
this.setState({ clicks: this.state.clicks - 1 });
}
toggleClick = () => {
this.setState({ show: !this.state.show });
}
render() {
return (
<div>
<button onClick={this.incrementValue}>Click to increment by </button>
<button onClick={this.decreaseValue}>Click to decrease by </button>
<button onClick={this.toggleClick}>
{ this.state.show ? 'Hide number' : 'Show number' }
</button>
{ this.state.show ? <h2>{ this.state.clicks }</h2> : '' }
</div>
);
}
}
export default App;
This is how you increase and decrease number on click in React
React Native Select Dropdown for Android and iOS