Skip to content

Instantly share code, notes, and snippets.

@MForMarlon
Last active February 17, 2022 19:15
Show Gist options
  • Save MForMarlon/e780c66c3dbca1f10f5bd7094d505458 to your computer and use it in GitHub Desktop.
Save MForMarlon/e780c66c3dbca1f10f5bd7094d505458 to your computer and use it in GitHub Desktop.
A react component that Increases/decreases integers in a text field
import React, { useState } from 'react'
import './NumberField.less'
export default function NumberField({
defaultValue = null,
allowNegatives = true,
allowZero = false,
onChange,
}) {
const [value, setValue] = useState(defaultValue || 0)
const increment = () => {
let newValue = value + 1
if (!allowZero && newValue === 0) {
newValue = 1
}
setValue(newValue)
onChange(newValue)
}
const decrement = () => {
let newValue = value - 1
if (!allowNegatives && allowZero && newValue <= 0) {
newValue = 0
} else if (!allowZero && newValue === 0) {
newValue = -1
}
setValue(newValue)
onChange(newValue)
}
return (
<div className="number-field">
<input type="text" className="number-field-input short-input" value={value} readOnly />
<button type="button" className="up-down-button up" onClick={increment}>&#x25B2;</button>
<button type="button" className="up-down-button down" onClick={decrement}>&#x25BC;</button>
</div>
)
}
.number-field {
position: relative;
.number-field-input {
box-sizing: border-box;
cursor: default;
font-family: Kievit, sans-serif;
font-size: 13px;
padding: 2px 4px;
text-align: center;
width: 50px;
}
.up-down-button {
border: 0;
color: #666;
font-size: 8px;
left: 50px;
margin: 0;
outline: 0;
position: absolute;
transition: all 0.25s ease-in-out;
}
.up-down-button:hover {
background: #666;
color: #fff;
cursor: pointer;
}
.up {
top: 0;
}
.down {
bottom: 0;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment