I want to create an app on React where a user can input a number of his bank card. In the input field will be a default value with 16 zeros and every next zero will immediately change to the inputed number.
import React, { useState } from 'react'
function CardNumber() {
const [value, setValue] = useState('')
const changeState = event => {
setValue(event.target.value)
}
return (
<input
value={value}
onChange={changeState}
placeholder='0000 0000 0000 0000'/>
)
}
export default CardNumber
2
Answers
I just added for you that input length doesn’t exceed 16 digits +3 spaces ( total 19) and the formatted Value is 4 digits grouped. I hope this will do the job for you
Using the
onKeyUp
event, you can access theevent.key
that was pressed by the user.So the idea here, is to store those numbers in an array first.
Then on render, use that array to format what is to be shown.
You wish to have some zeros after the entered digits. So on render, the input always is 19 characters (including 3 space)…
Your users are then loosing the ability to place the cursor in the middle of the credit card number to change a specific digit.
Note that this maybe considered bad UI, but it may be your choice to do it anyway. But the walk around here is extra simple, thanks to CSS:
So the caret not being visible… the user will not be tempted to place it in the middle.
This may be acceptable.
I made sure to allow the
Backspace
key to have an effect.I also added a visual indication for the user to know the card number is complete:
Here is the code… The demo is on CodeSandbox.