Skip to content

Instantly share code, notes, and snippets.

@allaniftrue
Created June 3, 2021 06:46
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save allaniftrue/fcef1a5ab4aa28298bb4d4ed783b970a to your computer and use it in GitHub Desktop.
Save allaniftrue/fcef1a5ab4aa28298bb4d4ed783b970a to your computer and use it in GitHub Desktop.
Reactjs prevent characters on keypress
use { useState } from 'react';
const Test = () => {
const [tipAmount, setTipAmount] = useState('');
const handleKeypress = (e) => {
if(!((e.keyCode > 95 && e.keyCode < 106)
|| (e.keyCode > 47 && e.keyCode < 58)
|| e.keyCode == 8)) {
e.preventDefault(); // Let's stop this event.
e.stopPropagation(); // Really this time.
return false;
}
}
const handleChange = (e) => {
setTipAmount(e.targe.value)
}
return (
<input
className="form-control"
name="tipAmount"
autoComplete="off"
id="tipAmount"
maxLength="20"
min="0.1"
placeholder="Enter amount"
type="number"
onChange={handleChange}
onKeyDown={handleKeypress}
value={tipAmount}
/>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment