Created
June 3, 2021 06:46
-
-
Save allaniftrue/fcef1a5ab4aa28298bb4d4ed783b970a to your computer and use it in GitHub Desktop.
Reactjs prevent characters on keypress
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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