How to Create an Increment Decrement Control in React

In this blog post we are going to create an increment decrement control in React. This will be a profession reusable component so that you can use it anywhere in your project or in production. So let’s get started.

First thing we will add is styled components. You can read more using the link but the idea is to style components using CSS code. Let’s install it using npm:

npm install --save styled-components

Let’s create a folder called incrementor where we are going to put all the code related to this component. And within that we are going to create a couple of javascript files. Let’s create a file incrementor.js and start to populate it with code.

We are going to create a container that is going to hold the rest of the items like the buttons and value. The general structure looks like this:

<Container>
<Button>-</Button>
<Value>...</Value
<Button>+</Button>
</Container>

You can see in the code sandbox how I have created the basic styled components. The value will be kept in a state variable and is going to be set on button click events. One issue is that the value keeps going up and it also goes beyond 0.

We need two things, a min max and some sort of clamping. The min max will be passed by the client and we can have the clamping implemented internally. You can see that implemented in the clamp.js file. The idea is to compare the value to min and max and return the appropriate value. Here is the clamp function:

clamp = (min, max) => (v) => (v <= min ? min : v >= max ? max : v);

It would be nice to also disable the controls if we say reached the min max bounds. And this is what is accomplished by the disable variables. Now we need to propagate the value back to client and for the client has to pass in a value and an onChange method. You can see this in the component signature for Incrementor:

function Incrementor({ value, min, max, onChange }) { ... }

Every time button is pressed we call the onChange function and provide a clamped value. Then the client can use a state to do whatever it wants with the value. Here is the sandbox

React Incrementor Demo – Grepsoft

https://codesandbox.io/embed/increment-decrement-9pzly?fontsize=14&hidenavigation=1&theme=dark